Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the contentType of a jQuery ajax post so that ASP.NET MVC can read it?

I have some jQuery that looks like this:

$.ajax({
     type: "POST",
     url: "/Customer/CancelSubscription/<%= Model.Customer.Id %>",
     contentType: "application/json",
     success: refreshTransactions,
     error: function(xhr, ajaxOptions, thrownError) {
         alert("Failed to cancel subscription! Message:" + xhr.statusText);
     }
});

If the action being called causes an exception it will ultimately get picked up by the Global.asax Application_Error where I have some code like this:

var ex = Server.GetLastError();
if (Request.ContentType.Contains("application/json"))
{
     Response.StatusCode = 500;
     Response.StatusDescription = ex.Message;
     Response.TrySkipIisCustomErrors = true;
}
else
{
     // some other way of handling errors ...
}

When I execute the script that does the post the Request.ContentType is always an empty string and therefore does not hit the first if block. Is there some other value that I should be putting in the ajax "contentType"? Or is there another way for me to tell asp.net that the content type should be "application/json"?

Clarification

The goal I am trying to achieve is to pass the exception message back to the ajax error event. Currently, even though the IF block is being bypassed, the error event correctly throws an alert box but the message is "Not Found".

As you can see I am trying to set the exeception message to the Response.StatusDescription which I believe the xhr.statusText in the ajax error is set to.

like image 999
Sailing Judo Avatar asked Feb 04 '10 20:02

Sailing Judo


1 Answers

Accordiing to this article: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ "jQuery does not properly set the specified content-type when there is no data included. "

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});
like image 143
typeoneerror Avatar answered Oct 07 '22 19:10

typeoneerror