开发者

Textbox validation in MVC2

开发者 https://www.devze.com 2022-12-18 15:09 出处:网络
I have added Required attribute to one of my properties of Model class as follows - [Required(ErrorMessage=\"UserID should not be blank\")]

I have added Required attribute to one of my properties of Model class as follows -

[Required(ErrorMessage="UserID should not be blank")]
[DisplayName("User Name")]
public string UserName { get; set; }

Inside my view, which inherits the class containing above property, I have tried to apply validaton to a textbox as follows -

 <%= Html.TextBoxFor(model => Model.UserName, new { @class = "login-input",       @name="UserName" })%>
 <%= Html.ValidationMessageFor(model => Model.UserName)%>

But when I run this app, and invokes the post(using a button click), without entering anything in the textbox; I don't get the text box validated?

Can anyone p开发者_如何转开发lease tell me what may be the reason that is prohibiting the textbox validation?

Thanks in advance, kaps


change model => Model.UserName to model => model.UserName


dont forget to include MicrosoftMvcValidation.js MicrosoftAjax.js into your master page .

And as mentioned by Rashmi's logic - use model binding to make validation work.

[HttpPost] public ActionResult AddUser(User user) {
... }


This will work only if the HttpPost Action method takes the class (which contains the property UserName) as one of its input parameters.

So if your code is something like this:

public class User
{
  public User() { } // Make sure the class has an empty constructor

  [Required(AllowEmptyStrings = false, ErrorMessage="UserID should not be blank")] 
  [DisplayName("User Name")] 
  public string UserName { get; set; } 
}

Then the following action method will validate UserName:

[HttpPost]
public ActionResult AddUser(User user)
{ 
  ...
}

If your action method is something like this, it will NOT consider your validation attributes:

[HttpPost]
public ActionResult AddUser(string userName)
{ 
  ...
}

Also, model => Model.UserName or model => model.UserName does not make a difference.


Try removing the '@name="UserName"' from your Html.TextBoxFor


Required does not mean what you think it does. Read the update.


I failed to mention that the post method is receiving formcollection as parameter. I replaced that with the class containing the property. The problem gets solved. Apologies.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号