在新创建的 MVC 项目中,在"帐户注册"页面中,如果我不填写任何信息并单击"注册"按钮,我将看到
•用户名字段为必填字段。
•密码字段为必填字段。
这些从哪里来?
如果您查看注册操作结果(在 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,基本上它会检查或模型有任何验证问题。
该模型可以在帐户模型中找到
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
对象中 它是视图中调用的 ValidationMessageFor()
帮助程序方法调用的 ValidationExtensions
方法的返回值。
辅助模型中查找顶部的[必需]。