C# Mvc 3发布内容类型应用程序/json,操作方法参数松散映射?
我有一个有趣的情况,这让我很困惑。 似乎发布C# Mvc 3发布内容类型应用程序/json,操作方法参数松散映射?,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我有一个有趣的情况,这让我很困惑。 似乎发布appliction/jsoncontent-type会使基本路由引擎无法绑定操作方法参数 使用默认路线: Routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optiona
appliction/json
content-type会使基本路由引擎无法绑定操作方法参数
使用默认路线:
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
}
我正在将json对象发布到这个url/Test/SaveItem/1
+上
我需要id
和JsonDto
的原因是id
参数引用了JsonDto
对象需要关联的父对象
我想我可以将dto更改为包含父id作为属性,并解决整个问题
当我发布一个
应用程序/json
请求时,id
参数没有被填充,这让我觉得很奇怪。好的,您还没有展示如何调用此操作,所以我们只能在这里猜测。下面是一个对我来说非常好的示例,它按照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>
$.ajax({
url:'@url.Action(“SaveItem”,新的{id=123})',
键入:“POST”,
contentType:'application/json;charset=utf-8',
数据:JSON.stringify({
福:“酒吧”
}),
成功:功能(结果){
//TODO:处理结果
}
});
我已经解决了我的问题
问题在于,发布到action方法的Json数据包含一个Id
属性,以及默认路由的id
路由值。所以在绑定JSON时
对象,其Id
属性将赢得URL中的路由值。因此,要调整Darin的示例:
<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>
将默认的id
路由参数重命名为urlId
并更新我的操作方法解决了问题
冲突。我将该方法作为REST请求调用,本质上是对/Home/SaveItem/123的WebRequest,内容类型设置为application/json,实体主体设置为json字符串。我将尝试删除端点上的OAuth安全性,看看是否可以在响应中执行jquery ajax调用中的示例,看看它是否有效。有趣的是,这在客户端有效,但不是通过webrequest。。我一定不是在以某种方式创建正确类型的请求。
Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{urlId}", // URL with parameters
new { controller = "Home", action = "Index", urlId = UrlParameter.Optional } //
);