验证消息来自何处?

时间:2013-02-01 19:16:42

标签: c# asp.net asp.net-mvc

在新创建的MVC项目中,在“帐户注册”页面中,如果我没有填写任何信息并单击“注册”按钮,我会看到

  

•用户名字段是必需的。

     

•密码字段是必需的。

这些来自哪里?

3 个答案:

答案 0 :(得分:4)

如果你看一下Register ActionResult(在AccountController.cs中)

  [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid) // here it will check it lal
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    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);
        }

您会看到ModelState.IsValid,基本上它会检查或模型有任何验证问题。

该模型可以在AccountModels

中找到
public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { 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; }
}

正如你所看到的,他们都有一个require标签,所以他们会返回false并在旁边显示它是必需的(当它没有填写时)

编辑: 既然你想知道为什么它是那个文本而不是其他文本,那么它是默认文本,所以问问microsoft :),无论如何你可以通过将ErrorMessage参数添加到Required标签来修改文本。

示例:

[Required(ErrorMessage = "Hey you forgot me!")]

答案 1 :(得分:2)

实际的消息字符串存储在MvcHtmlString中的System.Web.Mvc.ModelStateDictionary.对象中。它是由ValidationExtensions辅助方法调用的ValidationMessageFor()方法的返回值。观点。

答案 2 :(得分:0)

查看顶部[required]的关联模型。