views:

467

answers:

5

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?

A: 

Are your MIME-types set on your server properly?

Daniel A. White
+2  A: 

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:

$("#editPageContentForm").submit(function(event) {
    event.preventDefault();
    $.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.");
      }
  } );
Craig Stuntz
A: 

Try throwing a return false; at the end of your $("#editPageContentForm").submit() function.

swilliams
A: 

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".

Cleiton
A: 

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.

Adrian Grigore