Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net ApplicationUser的自定义和唯一字段_Asp.net_Asp.net Mvc_Entity Framework - Fatal编程技术网

Asp.net ApplicationUser的自定义和唯一字段

Asp.net ApplicationUser的自定义和唯一字段,asp.net,asp.net-mvc,entity-framework,Asp.net,Asp.net Mvc,Entity Framework,我正在为我的申请创建一个登记表。我有一个字段必须是唯一的,并创建了自定义验证以确保这一点。当我提交具有唯一值的表单时,页面不会更改或提交任何内容。到目前为止,我的ViewModel看起来像这样 public class RegisterViewModel { [Required] [CustomValidation(AccountController, "checkifusernametaken", ErrorMessage = "In use already")]

我正在为我的申请创建一个登记表。我有一个字段必须是唯一的,并创建了自定义验证以确保这一点。当我提交具有唯一值的表单时,页面不会更改或提交任何内容。到目前为止,我的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")
}
//POST:/Account/Register
[HttpPost]
[异名]
[ValidateAntiForgeryToken]
公共异步任务寄存器(RegisterViewModel模型)
{
if(ModelState.IsValid)
{
var user=新应用程序用户
{
UserNameIdentity=model.UserNameIdentity,
用户名=model.Email,
Email=model.Email,
FirstName=model.FirstName
};
var result=await UserManager.CreateAsync(用户、模型、密码);
if(result.successed)
{
//将注册用户添加到默认用户角色
UserManager.AddToRole(user.Id,“user”);
等待SignInManager.SignInAsync(用户,isPersistent:false,rememberBrowser:false);
返回重定向到操作(“索引”、“主页”);
}
加法器(结果);
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}
@模型Project.RegisterViewModel
@{
ViewBag.Title=“寄存器”;
}
@ViewBag.Title。
@使用(Html.BeginForm(“Register”、“Account”、FormMethod.Post、new{@class=“form horizontal”、role=“form”}))
{
@Html.AntiForgeryToken()
创建一个新帐户。

@Html.ValidationSummary(“,new{@class=“text danger”}) @LabelFor(m=>m.FirstName,新的{@class=“col-md-2控制标签”}) @TextBoxFor(m=>m.FirstName,新的{@class=“form control”}) @LabelFor(m=>m.UserNameIdentity,新的{@class=“col-md-2控制标签”}) @TextBoxFor(m=>m.UserNameIdentity,新的{@class=“form control”}) @LabelFor(m=>m.Email,新的{@class=“col-md-2控制标签”}) @TextBoxFor(m=>m.Email,新的{@class=“form control”}) @LabelFor(m=>m.Password,新的{@class=“col-md-2控制标签”}) @Html.PasswordFor(m=>m.Password,新的{@class=“form control”}) @LabelFor(m=>m.ConfirmPassword,新的{@class=“col-md-2控制标签”}) @Html.PasswordFor(m=>m.ConfirmPassword,new{@class=“form control”}) } @节脚本{ @Scripts.Render(“~/bundles/jqueryval”) }
创建一个自定义的
验证属性
,该属性将检查输入的用户名:

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; }

您的模型到达控制器时为空?请同时发布视图代码。一旦我删除自定义验证,它就可以正常工作,让register控制器打开以接受来自不同用户的匹配usernameIdentity值。模型到达控制器时不是空的。我现在发布查看代码完美,当我得到你的答案时,我刚刚创建了这个扩展类