ASP.NET MVC模型状态验证

时间:2011-03-21 13:55:31

标签: asp.net-mvc

<%= 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();
            }
        }

以上是注册表,我正在对其进行验证。它在控制器方法中运行良好,但在发送回寄存器页面时不会显示错误消息。我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

什么是_modelState?为什么不使用ModelState

或仅Data Annotations进行客户端验证。

在此代码中,您没有返回ModelState,这就是没有显示错误的原因。只需使用ModelState代替_modelState,您应该全部设置。:

            if (_modelState.IsValid)
            {
                //blah
            }
            else
            {
                var roles = _UsrService.GetRoles().ToList();
                ViewData["Roles"] = new SelectList(roles);
                return View();
            }