MVC3查询字符串参数和输入字段共享相同的名称
我有一个名为“from”(起始日期)的查询参数 还有一个绑定到名为 From 的属性的输入,
在我的 ViewModel 构造函数中,我将 From 属性设置为日期...
如果查询参数名称和属性名称不同,但如果它们是相同的 MVC3 且带有一些魔法,则此方法有效无论查询参数中有什么值并与之绑定,它都不关心 From 属性中有什么值。为什么?这种自动魔法在很多层面上都是错误的!我该如何禁用它?
编辑:属性获取什么值并不重要,如果存在与输入具有相同 id 的查询字符串,MVC 自动获取该值并将其分配给输入元素
I have a queryparameter named "from" (a from date)
and also a input which binds to a property named From
In my ViewModel contructor i set the From property to a date...
This works if the query parameter name and the property name are different, but if they are same MVC3 with some magic takes whatever value there are in the query param and binds against that, it does not care what value are in the From property.. Why? this atuomagic is so wrong on so many levels! How do I disable it?
edit: It doesnt matter what value the Property gets, if a querystring exists with the same id as the input MVC automatic takes that value and assign it to the input element
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MVC 按照约定工作,并通过名称将值绑定到模型。要了解正在发生的情况,我建议您阅读 Phil Haack 的这篇博客文章:值提供程序和模型绑定程序之间有什么区别?
在同一个元素中包含两个具有相同名称的不相关元素是不好的做法请求,因为名称冲突很可能会导致意想不到的问题。最佳实践是重命名这些元素之一,以便消除名称冲突。
MVC works by convention, and binds values to the model by names. To understand what is happening, I suggest you read this blog article from Phil Haack: What’s the Difference Between a Value Provider and Model Binder?
It is bad practice to have two unrelated elements with identical names in the same request, as a name collision is very likely to cause unexpected problems. Best practice is to rename one of these elements so that you eliminate the name collision.
您需要
在从控制器操作返回之前调用。
问题是 ModelState 具有来自查询字符串的值,并且在发生绑定时该值优先于模型中的值。
这是错误还是功能取决于您的观点... http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx< /a>
You need to call
Before returning from your controller action.
The issue is that the ModelState has the value from the query string, and that takes precedence over the value in your model when binding occurs.
Whether this is a bug or a feature depends on your point of view... http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx