2013-02-01 28 views
2

在新创建的MVC项目,在帐号注册页面,如果我没有在任何填写信息,然后点击注册按钮,我会看到验证消息来自哪里?

•您需要输入用户名称字段。

•密码字段是必需的。

这些来自哪里?

回答

2

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

+0

哦,谢谢你,我现在看到它了,但现在我想删除那个消息中的“field”这个词?我怎样才能做到这一点 ? –

+2

您不能更改默认消息,但可以用自己的消息覆盖它。在模型中,只需指定要显示的消息:'[必需(ErrorMessage =“用户名是必需的”)]' –

4

如果你看看在册的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,basicly它检查或模型有任何验证问题。

该模型可以在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; } 
} 

正如你可以看到他们俩都在它旁边,它是需要一个需要标记,以便他们将返回false和显示(当它不填写)

编辑: 因为你想知道为什么它是文本,而不是其他文本,它是默认文本,所以要求微软:),无论如何,你可以修改文本,只要你喜欢通过添加ErrorMessage参数必需的标签。

实施例:

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

谢谢,我知道它来自'[必需]',我想知道这些文本消息的存储位置。 –

+0

@BéVúSữa1看看HTML。你会看到那里的消息不显眼的JavaScript验证。 – MikeSmithDev

+0

我问这个问题,因为我认为至少我可以找到字符串'The + [name of control] + field is required',但是我在js文件 –

0

外表为[需要]在顶部的assiciated模型。