asp.net-mvc – HiddenFor(x => x.Id)正在由UrlParameter而不是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路由信息?

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

解决方法

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....