在一个新创建的MVC项目中,在Account Register页面中,如果我没有填写任何信息并点击Register按钮,我会看到
• 用户名字段是必需的。
•密码字段是必需的。
这些是从哪里来的?
在一个新创建的MVC项目中,在Account Register页面中,如果我没有填写任何信息并点击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!")]
实际的消息字符串存储在一个MvcHtmlString
对象中,它是视图中调用的辅助方法调用System.Web.Mvc.ModelStateDictionary.
的方法的返回值。ValidationExtensions
ValidationMessageFor()
在顶部的 [required] 的关联模型中查找。