如何在ModelState中更改一个值,使其有效,使用ASP。净MVC吗?

时间:2022-05-13 10:41:35

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.

我目前允许selectlist的初始值为“”。用户可以选择是填写此选项,还是将其保留为默认值。

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.

这个selectList在ID上工作,ID被传递给我的控制器。但是,由于没有选择int类型,因此ModelState的结果为False,因为输入是一个空字符串,而不是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

我想要将这个空字符串的值改为0。这将导致ModelState为真。我一直在查看ModelState dictionary类,以便在检查ModelState之前更改键值对。然而,我一直无法成功地使用它。https://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary(v = vs.118). aspx

Any help would be greatly appreciated.

如有任何帮助,我们将不胜感激。

2 个解决方案

#1


14  

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

http://geekswithblogs.net/bobhardister/archive/2013/03/11/retain -和-设置-复选框-价值- - - mvc 4. aspx

#2


4  

you could just remove the error

你可以去掉这个错误。

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

if (ModelState.IsValid)
{
}

#1


14  

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

http://geekswithblogs.net/bobhardister/archive/2013/03/11/retain -和-设置-复选框-价值- - - mvc 4. aspx

#2


4  

you could just remove the error

你可以去掉这个错误。

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

if (ModelState.IsValid)
{
}