asp.net MVC ModelState.IsValid returning false


asp.net MVC ModelState.IsValid returning false



I am working in an ASP.NET MVC Application. I have a view model as follows:

public class SampleInterestViewModel {    //Properties defined    //One such property that shows an error in ModelState is as follows    public DateTime? SampleDate { get; set; } } 

From UI Perspective user can enter date as mmddyyyy. And when user enters in such format say 01012001, my ModelState.IsValid code piece in controller returns false. When I did a quick watch in ModelState, I see an error for the propery "SampleDate", saying "The Value 01012001 is not valid for SampleDate".

In my modelbinder, during the OnModelUpdated event I tried to format the value 01012001 to 01/01/2001 and assigned it back to SampleInterestViewModel.SampleDate thinking that ModelState.IsValid might return true without that error. But still ModelState.IsValid is false and I when I looked in to the ModelState dictionary, this particular property still has that errors in its collection.

Lastly I tried to format 01012001 and update the value 01/01/2001 directly to the Property SampleDate in the ModelState dictionary. But still ModelState.IsValid is false showing the same error for the SampleDate property. Can't figure out why ModelState.IsValid works and how and when it gets set to false.

If the User enter 01012001 in the UI, I still need to format it in the modelbinder to 01/01/2001 and make sure that ModelState.IsValid it true so that the rest of my controller code can work as expected. In the UI I am doing an AjaxSubmit to post the sampleDate value.

Any thoughts or comments.


How to get Controller name, and data available in a base Controller?

1:

Anonymous Type syntax in ASP.NET MVC
I must see a few solutions:. can hidden variables value be accessed in a controller in MVC
  1. After fixing the format in your model binder, you could clear the ModelState error with ModelState["SampleDate"].Errors.Clear();.
  2. Use JavaScript to validate the input to force the user to enter the correct format.
  3. Use JavaScript to change the format for the user before form post.
I think a combination of 1 and 2 is your best bet.. var javascript to asp.net MVC model
Route always goes to the first maprouteHow to pass a delegate to create an expression tree that is a MethodCallExpression

2:

Forms Authentication & IIS7 (&MVC): Why ReturnUrl=/ is added?
Try using in your action a white list of parameters to bind, with . Can i access ValidationMessage through jquery in asp.net mvc
Bind(Include="param1,param2...") 
And in this list, ommit the parameter this you are binding by yourself. Read this ScottGu's post for more information..


90 out of 100 based on 65 user ratings 680 reviews

@