将JObject发布到某个操作

时间:2012-10-04 15:06:08

标签: asp.net-mvc json json.net

我正在读Rick Strahls

http://www.west-wind.com/weblog/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods

我希望能够将JObject用于该操作。 我写了一个像这样的控制器

public class AlbumsController : Controller
{
    [System.Web.Http.HttpPost]
    public string PostAlbum(JObject jsonData)
    {
        return "success";
    } 
}

前端看起来像这样

当调用ajax时出现错误

       $("#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://localhost:50066/Albums/PostAlbum 500 (Internal Server Error) 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

1 个答案:

答案 0 :(得分:5)

您的控制器应来自ApiController,而不是来自Controller

public class AlbumsController : ApiController

此外,如果您使用默认路线设置:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

我建议您使用RESTful操作名称:

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;
});