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 mvc ASP.NET MVC模型状态验证 帐户信息_Asp.net Mvc - Fatal编程技术网

Asp.net mvc ASP.NET MVC模型状态验证 帐户信息

Asp.net mvc ASP.NET MVC模型状态验证 帐户信息,asp.net-mvc,Asp.net Mvc,用户名: 名字 姓 电邮: 密码: 确认密码: 角色: 私有ModelStateDictionary\u modelState; public AccountController():此(null,null) { _modelState=newmodelstatedictionary(); } [接受动词(HttpVerbs.Post)] 公共操作结果寄存器(字符串用户名、字符串名、字符串名、字符串密码、字符串确认密码、字符串电子邮件、字符串角色) { 尝试 { i

用户名:

名字

电邮:

密码:

确认密码:

角色:

私有ModelStateDictionary\u modelState; public AccountController():此(null,null) { _modelState=newmodelstatedictionary(); } [接受动词(HttpVerbs.Post)] 公共操作结果寄存器(字符串用户名、字符串名、字符串名、字符串密码、字符串确认密码、字符串电子邮件、字符串角色) { 尝试 { if(string.IsNullOrEmpty(密码)) _AddModelError(“密码”,“passowrd字段为空”); if(string.IsNullOrEmpty(confirmPassword)) _AddModelError(“confirmPassword”,“confirmPassword字段为空”); if(string.IsNullOrEmpty(用户名)) _AddModelError(“用户名”,“用户名字段为空”); if(string.IsNullOrEmpty(电子邮件)) _modelState.AddModelError(“电子邮件”,“电子邮件字段不能为空”); Regex regEmail=new Regex(@“\w+([-+.]\w+)*@\w+([-.]\w+*\)。\w+([-.]\w+*”); 如果(!regEmail.IsMatch(电子邮件)) _modelState.AddModelError(“电子邮件”,“提交的电子邮件id格式无效”); if(string.IsNullOrEmpty(firstName)) _AddModelError(“名字”,“名字字段为空”); if(string.IsNullOrEmpty(lastName)) _AddModelError(“姓氏”,“姓氏字段为空”); 如果(!password.Equals(confirmPassword、StringComparison.InvariantCultureIgnoreCase)) _AddModelError(“密码”,“密码不匹配”); if(_modelState.IsValid) { int id=_UsrService.GetRoleId(角色); Data.User usr=新用户(用户名、姓氏、姓氏、电子邮件、DateTime.Now、null、id); string retRegister=_UsrService.RegisterUser(usr,password,confirmPassword,“none”,“none”); if(retRegister.Equals(“true”)) { UserRolesControl controll=新的UserRolesControl(Users(),Roles()); 返回视图(“控制”,控制); } 其他的 { AddModelError(“\u Form”,retRegister); ViewData[“PasswordLength”]=MembershipService.MinPasswordLength; var roles=_UsrService.GetRoles().ToList(); ViewData[“角色”]=新的选择列表(角色); 返回视图(); } } 其他的 { var roles=_UsrService.GetRoles().ToList(); ViewData[“角色”]=新的选择列表(角色); 返回视图(); } } 捕获(例外情况除外) { 返回视图(); } }
上面是一个注册表格,我正在对它进行验证。它在控制器方法中运行正常,但在发送回寄存器页面时不显示错误消息。我的代码有什么问题吗?

什么是
\u modelState
?为什么不改用
ModelState

或者只是为了客户端验证

在这段代码中,您没有返回ModelState,这就是没有显示错误的原因。只需使用
ModelState
而不是
\u ModelState
,您就可以完成所有设置:

<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>
    </div>
    <% using (Html.BeginForm("Register", "Account" , FormMethod.Post))
                       { %>     
        <div>
            <fieldset>
                <legend>Account Information</legend>
                <p>
                    <label for="username">User Name:</label>
                    <%= Html.TextBox("username") %>
                    <%= Html.ValidationMessage("username") %>
                </p>
                <p>
                    <label for="FirstName">First Name</label>
                    <%= Html.TextBox("firstName") %>
                    <%= Html.ValidationMessage("firstName") %>
                </p>
                <p>
                    <label for="LastName">Last Name</label>
                    <%= Html.TextBox("lastName") %>
                    <%= Html.ValidationMessage("lastName") %>

                </p>
                <p>
                    <label for="email">Email:</label>
                    <%= Html.TextBox("email") %>
                    <%= Html.ValidationMessage("email") %>
                </p>
                <p>
                    <label for="password">Password:</label>
                    <%= Html.Password("password") %>
                    <%= Html.ValidationMessage("password") %>
                </p>
                <p>
                    <label for="confirmPassword">Confirm password:</label>
                    <%= Html.Password("confirmPassword") %>
                    <%= Html.ValidationMessage("confirmPassword") %>
                </p>
                <p>
                    <label for="Role">Role:</label>
                    <%= Html.DropDownList("Role",((SelectList)ViewData["Roles"]),"--Select One---") %>
                </p>
                <p>
                    <input type="submit" value="Register" />
                </p>
            </fieldset>
        </div>
    <% } %>


  private ModelStateDictionary _modelState;

   public AccountController() : this(null, null)
        {
          _modelState = new ModelStateDictionary();

        }

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(string username, string firstName, string lastName, string password, string confirmPassword, string email, string role)
        {
            try
            {

                if (string.IsNullOrEmpty(password))
                    _modelState.AddModelError("password", "passowrd field is empty");
                if (string.IsNullOrEmpty(confirmPassword))
                    _modelState.AddModelError("confirmPassword", "Confim Passowrd field is empty");
                if (string.IsNullOrEmpty(username))
                    _modelState.AddModelError("username", "UserName field is empty");
                if (string.IsNullOrEmpty(email))
                    _modelState.AddModelError("email", "Email field cannot be  empty");
                Regex regEmail = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                if (!regEmail.IsMatch(email))
                    _modelState.AddModelError("email", " The email id submitted is not in valid format");

                if (string.IsNullOrEmpty(firstName))
                    _modelState.AddModelError("firstName", "First name field is empty");
                if (string.IsNullOrEmpty(lastName))
                    _modelState.AddModelError("lastName", "Last name field is empty");

                if (!password.Equals(confirmPassword, StringComparison.InvariantCultureIgnoreCase))
                    _modelState.AddModelError("password", "Password do not match");

                if (_modelState.IsValid)
                {
                    int id = _UsrService.GetRoleId(role);
                    Data.User usr = new User(username, firstName, lastName, email, DateTime.Now, null, id);
                    string retRegister = _UsrService.RegisterUser(usr, password, confirmPassword, "none", "none");

                    if (retRegister.Equals("true"))
                    {
                        UserRolesControl contrl = new UserRolesControl(Users(), Roles());
                        return View("Control", contrl);
                    }
                    else
                    {
                        ModelState.AddModelError("_Form", retRegister);
                        ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
                        var roles = _UsrService.GetRoles().ToList();
                        ViewData["Roles"] = new SelectList(roles);
                        return View();
                    }
                }
                else
                {
                    var roles = _UsrService.GetRoles().ToList();
                    ViewData["Roles"] = new SelectList(roles);
                    return View();
                }                
            }
            catch (Exception ex)
            {
                return View();
            }
        }
            if (_modelState.IsValid)
            {
                //blah
            }
            else
            {
                var roles = _UsrService.GetRoles().ToList();
                ViewData["Roles"] = new SelectList(roles);
                return View();
            }