views:

27

answers:

3

I'm using jQuery's form plugin (as suggested in a number of threads like this one) to make an Ajax post to a .NET MVC controller and consume the JSON I get back. It works just fine in Chrome, but in some other browsers, including Firefox 3, the form submit results in a "Save or Open this file" dialog box. The JavaScript looks like:

var options = {
            dataType: "json",
            clearForm: true,
            beforeSubmit: hideUpdateField,
            success: handleNewsPostSuccess
        };

        $('div#Updates form').ajaxForm(options);

and meat of the controller response is:

Object response = new { html = RenderPartialViewToString("DisplayNewsPost", np), newpoints = points.ToString() };
return Json(response, "application/json; charset=utf-8");

What am I missing? It's like the submit event isn't getting attached in Firefox and the other problem browsers. I tried making my own submit action using ajaxSubmit instead with a return false in it, but no difference.

A: 

I'm not sure if you're hitting the same problem, but this question and answers may help you

samy
+1  A: 

Use different MIME type for response; simple text/plain should work. I believe FF is confused by unknown application/* MIME type and thus assumes it's some application-specific data that are best downloaded as separate file.

Alternatively, you can experiment with Content-Disposition header, setting it to inline. Firefox should be obeying it, but IIRC there might be some problems with it on IE.

Xion
A: 

The Json method already sets the proper content type so you don't need to repeat it:

return Json(response);

But from the behavior you are describing (Save As dialog) I suspect that the form is actually not posted using AJAX but a normal POST. This could be due to the fact that the DOM was not ready when you applied the .ajaxForm function. Make sure that you are ajaxifying the form inside $(document).ready:

$(function() {
    var options = {
        dataType: "json",
        clearForm: true,
        beforeSubmit: hideUpdateField,
        success: handleNewsPostSuccess
    };
    $('div#Updates form').ajaxForm(options);
});

Also if in your handleNewsPostSuccess callback you recreate the form in the DOM the ajaxForm might no longer apply to it and the second time you try to submit it will perform a normal POST.

Darin Dimitrov