HiddenFor(X => x.Id)正在由UrlParameter代替的视图模型填充 [英] HiddenFor(x => x.Id) is being populated by the UrlParameter instead of the ViewModel
问题描述
public ActionResult SomeAction(int Id){
//Id is set to 2
var model = //get some thing from db using Id(2);
//Now model.Id is set to 9;
return View(model);
}
----------View----------
@Html.HiddenFor(x => x.Id)
当我查看源代码,这个隐藏字段设置为2不9.如何得到它映射到模型,而不是映射到URL路由信息?
When I view source this hidden field is set to 2 not 9. How do I get it to map to the model instead of mapping to the URL routing info?
P.S。我想preFER不要因为那时我失去了我的好看的URL,除非我改变路由信息重命名参数。我已经做到了,它的工作,但不是我想要的。
P.S. I'd prefer not to rename parameters because then I lose my nice looking url's unless i change the routing info. I have done that and it does work, but not what I want.
推荐答案
在一个动作
被称为框架构建了一个 ModelStateCollection
根据查询字符串值,数据后,路由等价值观而这个 ModelStateCollection
将传递到查看
。所有HTML输入助手尝试将得到的值 ModelStateCollection
第一个后,试图从实际的模型得到的值之前。
When an Action
gets called the framework builds a ModelStateCollection
based on the query-string values, post-data, routing values etc. And this ModelStateCollection
will be passed to the View
. All the HTML input helpers try to the get the values from the ModelStateCollection
first, before trying to get the values from the actual model.
由于您的输入模型是内部编号
但产出模型是助手将使用值从 ModelStateCollection $一些新模式C $ C>(从查询字符串),因为属性格式名称
编号
的匹配。
Because your input model is the int id
but the output model is some new model the helpers will use the values from the ModelStateCollection
(from the query string) because the propery names Id
are match.
要使它工作,你必须手动清除 ModelStateCollection
新模式返回到视图之前:
To make it work you have to manually clear the ModelStateCollection
before returning the new model to the view:
public ActionResult SomeAction(int Id){
//Id is set to 2
ModelState.Clear();
var model = //get some thing from db using Id(2);
//Now model.Id is set to 9;
return View(model);
}
这篇关于HiddenFor(X => x.Id)正在由UrlParameter代替的视图模型填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!