Browser prompting download of JSON response, ASP.NET MVC2

I’ve encountered this problem all of a sudden doing a simple ajax submit of a form. The JSON comes back formatted correctly but the browser prompts to download it. Fiddler shows the content-type as correct:application/json; charset: utf-8Here’s my javascript: $(“#submitbutton”).click(function(e) $.post(‘FormTest’, function(o) FormCallback(o); );}); Here is …

via C Programming Language Tutorial » Search Results » ajax:

Browser prompting download of JSON response, ASP.NET MVC2

I’ve encountered this problem all of a sudden doing a simple ajax submit of a form. The JSON comes back formatted correctly but the browser prompts to download it. Fiddler shows the content-type as correct:
application/json; charset: utf-8Here’s my javascript:
$(“#submitbutton”).click(function(e)
$.post(‘FormTest’, function(o)
FormCallback(o);
);
}); Here is the server side:
public JsonResult FormTest(string test)
return Json(“This worked!”);
Again, I get back an object from the server fine, but it either prompts me to download (Firefox) or simply shows the object in a new tab in the browser (Chrome).
I found one other question like this but the author didn’t explain what was wrong. This is crazy! Any ideas?
Edit: The correct code is below, beside the e.preventDefault, I also needed to tell it which form data to use:
$(“#submit-button”).click(function(e)
$.post(‘address’, $(“#form”).serialize(), function(o)
FormCallback(o);
);
e.preventDefault();
});
………………………………………

You want to cancel the default action, I expect:
$(“#submitbutton”).click(function(e)
$.post(‘FormTest’, function(o)
FormCallback(o);
);
return false; // <<=====
});You can also try:
e.preventDefault();if that doesn’t work by itself
………………………………………

In addition to @Marc’s answer I would like to add that:
return Json(“This worked!”);in fact doesn’t work as it doesn’t return a valid JSON object. It simply returns “This worked!” to the client. You need to construct the object:
return Json(new Message = “This worked!” );
………………………………………

MVC 2 returns JSON mimetype by default. If you want to receive JSON data in plain HTML you should pass your JSON data as following:
return Json(model, “text/html”, JsonRequestBehavior.AllowGet);Another point, you can mark your Action with [ChildActionOnly] and call your action in your view this way
var json = <%= Html.Action("YourActionMethod", "YourControllerName") %>

For more info: Browser prompting download of JSON response, ASP.NET MVC2

C Programming Language Tutorial » Search Results » ajax

Browser prompting download of JSON response, ASP.NET MVC2

Share this post:

Related Posts

Leave a Comment