Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a value in the ModelState, so that it will be valid, using ASP.NET MVC?

I am currently allowing a selectlist to have an initial value of "". The user can choose whether to fill in this option or leave it on the default value.

This selectList works on an ID, where the ID is passed to my controller. However, as an int is not being selected, the ModelState results in False as the input was an empty string rather than an int.

I want to change the value of this empty string to be 0. This would result in the ModelState being True. I have been looking at the ModelState dictionary class, so that I can change the key, value pair before the ModelState is checked. However, I have been unable to use this successfully.
https://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary(v=vs.118).aspx

Any help would be greatly appreciated.

like image 310
Louise Avatar asked Jul 08 '15 21:07

Louise


2 Answers

Try using

ModelState.SetModelValue("PropertyID", new ValueProviderResult("New value", "", CultureInfo.InvariantCulture));

Here is a usefull article.

http://geekswithblogs.net/BobHardister/archive/2013/03/11/retain-and-set-posted-checkbox-value-in-the-mvc-4.aspx

like image 170
Garry Avatar answered Oct 12 '22 02:10

Garry


you could just remove the error

if (ModelState.ContainsKey("{key}"))
    ModelState["{key}"].Errors.Clear();

if (ModelState.IsValid)
{
}
like image 22
JamieD77 Avatar answered Oct 12 '22 01:10

JamieD77