ASP.NET MVC模型绑定器错误:绑定请求变量" ID"到型号的财产" ID和QUOT; [英] ASP.NET MVC ModelBinder bug: Binding request variable "id" to Model's property "Id"

查看:203
本文介绍了ASP.NET MVC模型绑定器错误:绑定请求变量" ID"到型号的财产" ID和QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC 3最终RTM版。

由于

这条路线:

  context.MapRoute(
    Blog_Posts
    博客/职位/ {ID} / {}塞,
    新{控制器=帖子,行动=索引,蛞蝓= UrlParameter.Optional}
);

和帖子的网页,例如/博客/职位/ 2 /我绑定在注释的局部视图部分段塞模型:

  @ Html.Partial(_ CommentEditor,新评论())

注释有一个公众诠释标识{搞定;设置;}

而在局部视图,我有这样的:

  @ Html.HiddenFor(注释= GT; comment.Id)

为什么会显示这个?

 <输入类型=隐藏值=2NAME =IDID =ID数据-VAL-所需=是必需的ID字段数据-VAL-数=ID字段必须是一个数字。数据-VAL =真>

为什么当我改变编号注释 CommentId 它有正确 0

我觉得默认的模型粘合剂结合到 {ID} 路由的。


解决方案

这是因为,当您使用HTML佣工如HiddenFor他们先了解一下路线数据和模型状态,之后在模型中。因此,他们在你的路由数据找到一个参数ID = 2和要传递的模型中使用此值,而不是的id = 0。

I am using MVC 3 final RTM.

Given

This route:

context.MapRoute(
    "Blog_Posts",
    "Blog/Posts/{id}/{slug}",
    new { controller = "Posts", action = "Index", slug = UrlParameter.Optional }
);

And on a post's page, e.g. /blog/posts/2/some-slug I bind a partial view with a Comment model:

@Html.Partial("_CommentEditor", new Comment())

And Comment has a public int Id {get; set;}.

And in the partial view, I have this:

@Html.HiddenFor(comment => comment.Id)

Why does it display this?

<input type="hidden" value="2" name="Id" id="Id" data-val-required="The Id field is required." data-val-number="The field Id must be a number." data-val="true">

And why when I change Id on Comment to CommentId does it correctly have a value of 0?

Me thinks the default model binder is binding to the {id} of the route.

解决方案

That's happens because when you are using HTML helpers such as HiddenFor they first look at route data and model state and after that in the model. So they find in your route data a parameter id=2 and use this value instead of the id=0 in the model you are passing.

这篇关于ASP.NET MVC模型绑定器错误:绑定请求变量&QUOT; ID&QUOT;到型号的财产&QUOT; ID和QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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