繁体   English   中英

验证消息从何而来?

[英]where are validation messages coming from?

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

•“用户名”字段为必填项。

•密码字段为必填项。

这些是哪里来的?

如果您查看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!")]

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

在相关模型的顶部查找[required]。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM