张贴JObject到动作 [英] posting a JObject to an action
问题描述
我在读里克Strahls
I was reading Rick Strahls
<一个href=\"http://www.west-wind.com/weblog/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods\" rel=\"nofollow\">http://www.west-wind.com/weblog/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
我想能够使用JObject中所涉及的操作。
我写了这样一个控制器
I would like to be able to use JObject in to the the action. I wrote a controller like this
public class AlbumsController : Controller
{
[System.Web.Http.HttpPost]
public string PostAlbum(JObject jsonData)
{
return "success";
}
}
前端看起来像这样
the front end looks like this
在阿贾克斯被调用我得到一个错误
when the ajax gets called I get an error
$("#a").click(function () {
var album = {
AlbumName: "PowerAge",
Entered: "1/1/1977"
}
$.ajax(
{
url: "Albums/PostAlbum",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ Album: album }),
success: function (result) {
alert(result.Result);
}
});
});
POST HTTP://本地主机:50066 /相册/ PostAlbum 500(内部服务器错误)
jQuery的-1.7.1.js:8102
发送的jQuery-1.7.1.js:8102
jQuery.extend.ajax的jQuery-1.7.1.js:7580
(匿名函数)的专辑:74
jQuery.event.dispatch的jQuery-1.7.1.js:3256
elemData.handle.eventHandle
POST http://localhost:50066/Albums/PostAlbum 500 (Internal Server Error)
jquery-1.7.1.js:8102
send jquery-1.7.1.js:8102
jQuery.extend.ajax jquery-1.7.1.js:7580
(anonymous function) albums:74
jQuery.event.dispatch jquery-1.7.1.js:3256
elemData.handle.eventHandle
推荐答案
您控制器应来自的 ApiController
,而不是从的 控制器
:
Your controller should derive from ApiController
, not from Controller
:
public class AlbumsController : ApiController
此外,如果你使用的是默认路由设置:
Also if you are using the default route setup:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我会建议你使用REST风格的动作名称:
I would recommend you to use RESTful action names:
public class AlbumsController : ApiController
{
[HttpPost]
public string Post(JObject jsonData)
{
return "success";
}
}
和则:
$('#a').click(function () {
var album = {
AlbumName: "PowerAge",
Entered: "1/1/1977"
}
$.ajax({
url: 'api/albums',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ Album: album }),
success: function (result) {
alert(result);
}
});
});
return false;
});
这篇关于张贴JObject到动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!