MVC 3发布内容类型application/json,操作方法参数是否松散映射? [英] Mvc 3 posting content type application/json, action method arguments loose mapping?
问题描述
我遇到了一个很有趣的情况,这使我感到困惑.似乎发布 appliction/json
内容类型会使基本路由引擎无法绑定操作方法参数.
I have an interesting situation that has me stumped.
It seems that posting appliction/json
content type makes the basic routing engine unable to bind action method arguments.
使用默认路由:
Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
我有一个如下所示的操作方法:
I have an action method that looks like this:
//Controller name: TestController
[HttpPost]
public ActionResult SaveItem(int id, JsonDto dto)
{
// if content type of the request is application/json id = 0, JsonDto is populated
// if content type of the request is application/x-www-form-urlencode id = 1
}
我要发布到此URL /Test/SaveItem/1
+ json对象.
I am posting to this url /Test/SaveItem/1
+ the json object.
我需要 id
和 JsonDto
的原因是 id
参数引用了 JsonDto
对象需要关联.
The reason that I need to id
and the JsonDto
is that the id
argument references the parent object that the JsonDto
object need to releate to.
我想我可以将dto更改为包含父ID作为属性,并解决整个问题.
I suppose I could change the dto to contain the parent id as a property and work around this whole problem.
当我发布 application/json
请求时,不会填充 id
参数,这让我感到很奇怪.
It just strikes me as strange that the id
argument does not get populated when I post a application/json
request.
推荐答案
我已经解决了我的问题.
I have figured out my problem.
问题是正在发布到操作方法的Json数据包含 Id
The problem is that the Json data that is being posted to the action method includes an Id
属性.因此,当绑定JSON
property, in addition to the id
route value from the default route. So when binding the JSON
对象,其 Id
属性胜过URL中的路由值.因此,调整Darin的示例:
object, its Id
property wins over the route value in the URL. So to tweak Darin's example:
<script type="text/javascript">
$.ajax({
url: '@Url.Action("SaveItem", new { id = 123 })',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
"Id": 456
}),
success: function (result) {
// TODO: handle the results
}
});
</script>
在执行操作方法时, int id
参数包含456而不是123,因为我
When the action method exectures, the int id
argument contains 456 and not 123 as I
(显然是错误地)期望的.
(apparently mistakenly) expected.
所以对我来说,解决方法是将默认路由更改为:
So the workaround for me was to change my default route to:
Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{urlId}", // URL with parameters
new { controller = "Home", action = "Index", urlId = UrlParameter.Optional } //
);
将默认的 id
路由参数重命名为 urlId
并更新我的操作方法解决了
Renaming the default id
route parameter to urlId
and updating my action methods solved the
与我发生冲突.
这篇关于MVC 3发布内容类型application/json,操作方法参数是否松散映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!