在控制器中将模型设置为True后,模型的Hidden bool字段仍为False

时间:2015-02-24 11:03:40

标签: c# asp.net-mvc asp.net-mvc-4 hidden-field html.hiddenfor

我在ViewModel类中有这个属性:

public bool AreSimilarEntitiesChecked { get; set; }

在我的控制器中,我设定了它的值' true'并使用模型返回视图:

model.AreSimilarEntitiesChecked = true;

return View(model).WithWarning("Check the similar mentors before saving!");

在我的视图上有一个表格,我放置了这个属性的隐藏字段:

@Html.HiddenFor(m => m.AreSimilarEntitiesChecked)

使用包含AreSimilarEntitiesChecked的模型返回View后,其值保持为False desipte我在控制器中设置了True值。

我不知道它可能有什么问题。

生成的HTML:

<input name="AreSimilarEntitiesChecked" id="AreSimilarEntitiesChecked"
 type="hidden" value="False" data-val-required="The AreSimilarEntitiesChecked
 field is required." data-val="true">

1 个答案:

答案 0 :(得分:5)

我无法确定这是你问题中的问题,但我会赌很多钱......

MVC的ModelState,它保留视图模型数据的表示,优先从POST数据中提取值,而不是从绑定模型中获取它们。也就是说,如果HTTP POST包含一个名为(不区分大小写)AreSimilarEntitiesChecked且值为False的字段,那么在渲染视图时,在viewmodel中将该属性设置为什么并不重要。 ModelState会将POSTed值更改为viewmodel值。

这种奇怪的行为的原因是,假设你有一个字段,用户应该输入一个整数,然后他们写“香蕉”。这将发送到服务器进行验证,但失败。我们想再次渲染视图,“banana”仍然在字段中,并且消息不是整数。但是如果视图优先呈现视图模型的数据,则这是不可能的,因为“banana”不是整数并且不能放在该viewmodel字段中。因此保留了POST值。

有两种方法可以解决这个问题。您可以特别为此字段修复它:

ModelState.Remove("AreSimilarEntitiesChecked");

或核选项:

ModelState.Clear();

此处有关此行为的更多信息:http://weblog.west-wind.com/posts/2012/Apr/20/ASPNET-MVC-Postbacks-and-HtmlHelper-Controls-ignoring-Model-Changes