ApplicationUser的自定义和唯一字段

时间:2017-04-14 16:22:38

标签: asp.net asp.net-mvc entity-framework

我正在申请表上创建一个注册表单。我有一个必须是唯一的字段,并创建了自定义验证以确保这一点。当我提交具有唯一值的表单时,页面不会更改或提交任何内容。到目前为止,我的ViewModel看起来像这样

    public class RegisterViewModel
 {
    [Required]
    [CustomValidation(AccountController, "checkifusernametaken", ErrorMessage = "In use already")]
    [Display(Name = "Username")]
    [MaxLength(15, ErrorMessage = "This field must be less than 15 characters in length"), MinLength(2, ErrorMessage = "This field must have a value greater than 2")]
    public string UserNameIdentity { get; set; }

    [Required]
    [Display(Name = "First Name")]
    [MaxLength(15, ErrorMessage = "This field must be less than 15 characters in length"), MinLength(2, ErrorMessage = "This field must have a value greater than 2")]
    public string FirstName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    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")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

在我的控制器中,我有自定义验证,如下所示:

    public JsonResult UserNameInUse(string usernameIn)
    {
        return Json(!context.Users.Any(u => u.UserNameIdentity == usernameIn), JsonRequestBehavior.AllowGet);
    }

我的异步寄存器方法在同一个控制器中:

        // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                UserNameIdentity = model.UserNameIdentity,
                UserName = model.Email,
                Email = model.Email,
                FirstName = model.FirstName
            };
            var result = await UserManager.CreateAsync(user, model.Password);


            if (result.Succeeded)
            {
                // add registering users to the default user role
                UserManager.AddToRole(user.Id, "User");

                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }



@model Project.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.UserNameIdentity, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserNameIdentity, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

1 个答案:

答案 0 :(得分:0)

创建一个自定义ValidationAttribute,用于检查输入的用户名:

public class UniqueUsernameAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Get the object
        var username = value as string;

        // Check if exists
        DbContext context = new DbContext();
        var user = context.Users.FirstOrDefault(u => u.UserNameIdentity == username)

        if (user == null)
            return ValidationResult.Success;
        else
            return new ValidationResult("Username already exists");
    }
}

然后你可以使用它:

[Required]
[UniqueUsernameAttribute]
[Display(Name = "Username")]
[MaxLength(15, ErrorMessage = "This field must be less than 15 characters in length"), MinLength(2, ErrorMessage = "This field must have a value greater than 2")]
public string UserNameIdentity { get; set; }