Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonResult shows up a file download in browser

I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:

Javascript:

 <script type="text/javascript">
        $(document).ready(function () {
            $("form[action$='CreateEnvelope']").submit(function () {
                $.ajax({
                    url: $(this).attr("action"),
                    type: "POST",
                    data: $(this).serialize(),
                    dataType: "json",
                    success: function (envelopeData) {
                        alert("test");
                    }
                });
            });
            return false;
        });
    </script>

Action method on controller:

public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
    {
        //create an envelope object and return
        return Json(envelope);
    }

If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?

like image 394
joshb Avatar asked Dec 07 '25 04:12

joshb


1 Answers

You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.

<script type="text/javascript">
    $(document).ready(function () {
        $("form[action$='CreateEnvelope']").submit(function () {
            $.ajax({
                url: $(this).attr("action"),
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function (envelopeData) {
                    alert("test");
                }
            });
            // IMPORTANT: return false to make sure the normal post doesn't happen!
            return false;
        });
        return false;
    });
</script>

You were almost there!

like image 55
Thomas Avatar answered Dec 08 '25 17:12

Thomas