加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – HiddenFor(x => x.Id)正在由UrlParameter而不

发布时间:2020-12-15 20:21:08 所属栏目:asp.Net 来源:网络整理
导读: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
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路由信息?

附:我不喜欢重新命名参数,因为我失去了我漂亮的网址,除非我改变路由信息.我已经做到了,它确实有效,但不是我想要的.

解决方法

当Action被调用时,框架基于查询字符串值,后数据,路由值等构建ModelStateCollection.此ModelStateCollection将被传递给View.在尝试从实际模型中获取值之前,所有HTML输入帮助者都尝试从ModelStateCollection获取值.

因为您的输入模型是int id,而是输出模型是一些新模型,帮助者将使用ModelStateCollection(从查询字符串)中的值,因为属性名称Id匹配.

为了使其工作,您必须在将新模型返回到视图之前手动清除ModelStateCollection:

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读