Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post JSON to ASP.NET MVC 4 action from JQuery

I'm working on an app that uses ASP.NET MVC 4. In some ways, I feel like I'm learning everything from scratch :). I'm told its worth it.

I need to post some JSON to an Action in my controller. My action looks like the following:

[Authorize]
public class MyController : Controller
{
    [HttpPost]
    public ActionResult RemoveItem(string itemID)
    {
      // Do stuff...
      return Json(new { Status = 1, Message="Success" });
    }
}

My JQuery code looks like the following:

function removeItem(id) {
  var json = { "itemID": id };
  $.ajax({
    type: "POST",
    url: "/myController/removeItem",
    contentType: "application/json; charset=utf-8",
    data: json,
    dataType: "json",
    success: removeItemCompleted,
    error: removeItemFailed
  });
}

function removeItemCompleted(results) {
}

function removeItemFailed(request, status, error) {
}

In Fiddler, I notice a 500 error is returned. The TITLE field in the response says: "Invalid JSON primitive: itemID".

What am I doing wrong?

Thank you!

like image 686
Bill Jones Avatar asked Feb 07 '13 13:02

Bill Jones


1 Answers

Be sure to send JSON:

data: json,

should be

data: JSON.stringify(json),

IE7 and below needs a shim: https://github.com/douglascrockford/JSON-js

NOTE: Dave A's answer is also correct, but doesn't directly answer your issue. I +1'ed it.

like image 94
Joe Avatar answered Sep 19 '22 02:09

Joe