MVC ModelState erroneously reports errors
-
15-07-2021 - |
Question
I am receiving a model from a view.
Some of the values are automatically filled in.
However, some of the required values need to be added manually, like so:
[HttpPost]
public ActionResult Foobar(FooModel model, FormCollection collection)
{
// "timePicker" is a dropdown list containing different times
var time = collection["timePicker"].Split(':');
model.Hours = int.Parse(time[0]);
model.Minutes = int.Parse(time[1]);
if (ModelState.IsValid)
{
... // Do stuff
}
}
So here's the problem:
ModelState.IsValid
is false.
I debugged it, and it claims that model.Minutes
and model.Hours
are not assigned to.
...Which isn't true, because I had just assigned them values!
I considered using ModelState.Clear()
, but I don't want to need to manually check whether all the rest of the information is valid.
Is there any other way to resolve the issue?
Solution
Well, the model binding, putting errors in ModelState
, has been done before entering your action.
So the Minutes
and Hours
errors are in the ModelState before you add values in Hours and Minutes (which makes it invalid).
You might just remove these errors (and not all errors, as Clear()
does) , by doing :
ModelState.Remove("Hours");
ModelState.Remove("Minutes");
Another way to resolve this would be to create (and use) a custom ModelBinder.