0

I was reading Rick Strahls

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

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://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

eiu165
  • 6,101
  • 10
  • 41
  • 59

1 Answers1

5

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

I would recommend you to use RESTful action names:

public class AlbumsController : ApiController
{
    [HttpPost]
    public string Post(JObject jsonData)
    {
        return "success";
    } 
}

and then:

$('#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;
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928