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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With