views:

436

answers:

6

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 please tell me what may be the reason that is prohibiting the textbox validation?

Thanks in advance, kaps

+1  A: 

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

ali62b
I did the changes but it failed to work.
kapil
A: 

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

David G
A: 

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

mxmissile
A: 

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.

kapil
+1  A: 

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.

Rashmi Pandit
+1  A: 

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) {
... }

swapneel