这是由设计MVC模型绑定? [英] Is this by design in MVC Model Binding?

查看:126
本文介绍了这是由设计MVC模型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的场景,我以前从未见过,但是同事刚打 - MVC3


  

      
  1. 创建一个动作方法MyAction(INT myProperty的= 0)

  2.   
  3. 创建具有myProperty的属性的模型

  4.   
  5. 通过这个模型来一个强类型视图的实例,但在code中的属性设置为10(不使用查询字符串参数!)

  6.   
  7. 在视图中,Html.TextBoxFor(X => x.MyProperty)

  8.   

本应在文本框中呈现10。

现在调用操作方法MyAction?myProperty的= 8

应该不是这仍然使10在文本框中?

我看到,我可以覆盖前pression发现的财产,并假设这是因为他们是同一个名字(查询字符串参数和模型属性) 。 Eveything然后在的ViewData ,但其覆盖其他。

这设计是?


解决方案

这是由设计 - 的 ModelState中是优先级最高的价值提供者模型性能,更高的甚至比自己的模型。如果没有查询字符串参数,ModelState中不包含 myProperty的价值,所以框架使用模式的价值。

您可以使用 ModelState.Remove(myProperty的)来保证使用模型值

A simple scenario that I've never seen before, but a colleague has just hit - MVC3

  1. Create an action method MyAction(int myProperty = 0)
  2. Create a model that has a property MyProperty
  3. 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!)
  4. 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 the ViewData 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆