MVC 3发布内容类型application / json,操作方法参数是否松散映射?

问题描述

| 我遇到了一个有趣的情况,这使我感到困惑。 似乎发布“ 0”内容类型使基本路由引擎无法绑定操作方法参数。 使用认路由:
Routes.MapRoute(
  \"Default\",// Route name
   \"{controller}/{action}/{id}\",// URL with parameters
    new { controller = \"Home\",action = \"Index\",id = UrlParameter.Optional } // Parameter defaults
);
我有一个动作方法,看起来像这样:
//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对象。 我需要
id
JsonDto
的原因是
id
参数引用了
JsonDto
对象需要依赖的父对象。 我想我可以将dto更改为包含父ID作为属性,并解决整个问题。 当我发布
application/json
请求时,pop4ѭ参数没有被填充,这让我感到奇怪。     

解决方法

        好的,您尚未显示如何调用此操作,因此我们只能在这里猜测。这是一个对我来说很好用的示例,并按
SaveItem
方法中的预期填充了所有内容: 模型:
public class JsonDto
{
    public string Foo { get; set; }
}
控制器:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult SaveItem(int id,JsonDto dto)
    {
        return Content(\"success\",\"text/plain\");
    }
}
索引视图:
<script type=\"text/javascript\">
    $.ajax({
        url: \'@Url.Action(\"SaveItem\",new { id = 123 })\',type: \'POST\',contentType: \'application/json; charset=utf-8\',data: JSON.stringify({
            foo: \'bar\'
        }),success: function (result) {
            // TODO: handle the results
        }
    });
</script>
    ,        我已经解决了我的问题。 问题在于,要发布到操作方法的Json数据包含“ 14” 属性,以及默认路由中的“ 4”路由值。所以当绑定JSON时 对象的“ 14”属性赢得URL中的路由值。因此,调整达林的示例:
<script type=\"text/javascript\">
    $.ajax({
        url: \'@Url.Action(\"SaveItem\",data: JSON.stringify({
            \"Id\": 456
        }),success: function (result) {
            // TODO: handle the results
        }
    });
</script>
执行该操作方法时,
int id
参数包含456而不是123,因为I (显然是错误地)预期。 所以对我来说,解决方法是将默认路由更改为:
Routes.MapRoute(
  \"Default\",// Route name
  \"{controller}/{action}/{urlId}\",// URL with parameters
  new { controller = \"Home\",action = \"Index\",urlId = UrlParameter.Optional } // 
);
将默认的“ 4”路由参数重命名为“ 21”,并更新了我的操作方法,解决了 对我来说有冲突。