asp.net MVC ModelState.IsValid returning false

我只是一个虾纸丫 提交于 2019-12-12 10:00:49

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2883630/asp-net-mvc-modelstate-isvalid-returning-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!