我正在尝试检查注册时是否存在电子邮件,以便数据库中没有重复的电子邮件。我正在使用 MVC4 默认 Internet 应用程序执行此操作,但我已向 RegisterviewModel 添加了一个电子邮件字段。我还注意到,用户名字段做得很好,但我不知道他们是怎么做到的。我试图关注下面的这个博客,但没有运气,因为当我点击创建时没有响应。拖船伯克。当我使用萤火虫时,我得到Status: 302 Found
了Json action excutes
这就是我所拥有的:
用户资料
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
注册视图模型
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[Remote("DoesUserEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email address already exists. Please enter a different Email address.")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
注册动作
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try //CreateUserAndAccount
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
json动作
[HttpPost]
public JsonResult DoesUserEmailExist(string email)
{
var user = Membership.GetUserNameByEmail(email);
return Json(user == null);
}
编辑:添加了注册视图
@model Soccer.Models.RegisterModel
@{
ViewBag.Title = "Register";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>Create a new account.</h2>
</hgroup>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
有什么我不应该做的事情,还是我可以在这里采取另一个更简单的选择?