asp.net MVC ModelState.IsValid returning false

2019-05-19 12:51发布

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-19 13:17

Try using in your action a white list of parameters to bind, with

Bind(Include="param1,param2...")

And in that list, ommit the parameter that you are binding by yourself. Read this ScottGu's post for more information.

查看更多
时光不老,我们不散
3楼-- · 2019-05-19 13:26

I can see a few solutions:

  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.

查看更多
登录 后发表回答