I use ASP.NET MVC to post JSON from jQuery, and get some JSON back, using this little library function:
(function($) {
$.postJson = function(url, data) {
return $.ajax({
url: url,
data: JSON.stringify(data),
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
};
})(jQuery);
So obviously I'll call this like:
$('#button').click(function() {
$.postJson('/controller/action', { Prop1: 'hi', Prop2: 'bye' })
.done(function(r) { alert('It worked.'); })
.fail(function(x) { alert('Fail! ' + x.status); });
});
ASP.NET MVC 3 and ASP.NET MVC 4 support the submit side of things (before that you needed to extend ASP.NET MVC to handle submitting JSON), but the problem I'm running into is on the return. On the Controller I often return null to basically say "Success, nothing else to say," like:
[HttpPost]
public JsonResult DoSomething(string Prop1, string Prop2)
{
if (doSomething(Prop1, Prop2)
return Json(null); // Success
return Json(new { Message = "It didn't work for the following reasons" });
}
I use this pattern frequently and it works fine - my success/done callback gets called and all is well. But recently I upgraded ASP.NET MVC and jQuery, and it's stopped working - instead my fail callback is getting called whenever I return Json(null);
. Furthermore, I've inspected the response and the statusCode getting returned is in fact 200, so the server isn't failing - jQuery's just saying it is.
$(document).ajaxError...
shows inexception.message
: "Unexpected end of input" whenJson(null)
is returned (just to mention it, it didn't help me to find the reason for the problem). – Neom