这是由设计MVC模型绑定? [英] Is this by design in MVC Model Binding?
问题描述
一个简单的场景,我以前从未见过,但是同事刚打 - MVC3
- 创建一个动作方法MyAction(INT myProperty的= 0)
- 创建具有myProperty的属性的模型
- 通过这个模型来一个强类型视图的实例,但在code中的属性设置为10(不使用查询字符串参数!)
- 在视图中,Html.TextBoxFor(X => x.MyProperty)
块引用>本应在文本框中呈现10。
现在调用操作方法MyAction?myProperty的= 8
应该不是这仍然使10在文本框中?
我看到,我可以覆盖前pression发现的财产,并假设这是因为他们是同一个名字(
查询字符串
参数和模型属性) 。 Eveything然后在的ViewData code>,但其覆盖其他。
这设计是?
解决方案这是由设计 - 的 ModelState中是优先级最高的价值提供者模型性能,更高的甚至比自己的模型。如果没有查询字符串参数,ModelState中不包含
myProperty的
价值,所以框架使用模式的价值。您可以使用
ModelState.Remove(myProperty的)
来保证使用模型值A simple scenario that I've never seen before, but a colleague has just hit - MVC3
- Create an action method MyAction(int myProperty = 0)
- Create a model that has a property MyProperty
- Pass an instance of this model to a strongly typed view, but set the property to 10 in code (don't use the query string parameter!)
- In the view, Html.TextBoxFor(x => x.MyProperty)
This should render 10 in the text box.
Now call the action method MyAction?myProperty=8
Shouldn't this still render 10 in the text box?
I see that I can override the property discovered by the expression and assume this is because they are the same name (
Query String
parameter and model property). Eveything is then in theViewData
but one overrides the other.Is this by design?
解决方案This is by design - ModelState is the highest priority value-provider for model properties, higher than even model itself. Without query string parameter, ModelState does not contain value for
MyProperty
, so framework uses model value.You can use
ModelState.Remove("MyProperty")
to ensure using model value这篇关于这是由设计MVC模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!