I am trying to submit a form via jquery's ajax method in my .net mvc application. I've set the dataType to json and the contentType to "application/json; charset=utf-8". In my controller action, I'm returning a JsonResult.
For some reason, the JSON response doesn't get handled correctly and instead I get a dialog box to save a file with the JSON object inside of it.
$(document).ready(function() {
$("#editPageContentForm").submit(function() {
$.ajax(
{
type: "POST",
dataType: "json",
url: $("#editPageContentForm").attr("action"),
contentType: "application/json; charset=utf-8",
data: { ID: $("#id").val(), small_title: $("#small_title").val(), big_title: $("#big_title").val(), body: $("#body").val(), subheading: $("#subheading").val() },
success: function(result) {
alert('hi');
},
error: function(req, status, error) {
alert("Sorry! We could not receive your feedback at this time.");
}
}
);
})
In my controller action, I have something akin to:
public JsonResult Edit(int id, string small_title, string big_title, string subheading, string body)
{
return Json(new {success = true, message = "success"});
}
Why is the response not coming back as JSON?
This seems to be a browser problem, not a problem with your JsonResult. I've seen the same behavior on FireFox, but not on IE.
I had the same problem and wrote a blog post about it with more details. Anyway, here's the important bit:
So try changing the ContentType of the response.
It is coming back as JSON. But since you're doing this in a form submit, the browser is expecting HTML. The browser doesn't know how to visually render JSON, so it prompts you to save instead. Note that at this point your jQuery code is no longer running, because the page with the form was unloaded when the browser POSTed.
It's not entirely clear what you intend, but if you want to completely replace the non-AJAX submit with an AJAX-only submit, try changing your code to:
I don't know why, but in this topic, a similar problem was solved just setting the ContentType property of JsonResult to "application/json; charset=utf-8".
In my case, I just return from the action of the controller a ContentResult instead of JsonResult.
As you can see, I use Newtonsoft.Json for serializing my object but you can used the Json.Convert built in Asp.Net Mvc framework.
Then, in my javascript code, I have to call to $.parseJSON with the result of the server.
That's it! No additionnal parameters in the 'option' object like 'contentType: "text/html"'.
I'm not yet a pro for decrypting the http requests and I don't know if specifying the 'contentType' in the option change something but for me, it works.
Ok, that's it for 2 hours of my life lost for searching my xxxxx bugs related to Internet Explorer.
Are your MIME-types set on your server properly?