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 路由信息?
附言我不想重命名参数,因为除非我更改路由信息,否则我会丢失漂亮的 url。我已经这样做了,它确实有效,但不是我想要的。
最佳答案
当 Action
被称为框架构建了一个 ModelStateCollection
基于查询字符串值、后数据、路由值等。而这个 ModelStateCollection
将传递给 View
.所有 HTML 输入助手都尝试从 ModelStateCollection
中获取值。 第一 , 在尝试从实际模型中获取值之前。
因为您的输入模型是 int id
但是输出模型是一些新模型,助手将使用来自 ModelStateCollection
的值(来自查询字符串)因为属性名称 Id
是匹配的。
要使其工作,您必须手动清除 ModelStateCollection
在将新模型返回到 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);
}
关于asp.net-mvc - HiddenFor(x => x.Id) 由 UrlParameter 而不是 ViewModel 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8748940/