HiddenFor(X => x.Id)正在由UrlParameter代替的视图模型填充 [英] HiddenFor(x => x.Id) is being populated by the UrlParameter instead of the ViewModel

查看:91
本文介绍了HiddenFor(X => x.Id)正在由UrlParameter代替的视图模型填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 (从查询字符串),因为属性格式名称编号的匹配。

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屋!

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