Reputation: 107
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-8
Here'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();
});
Upvotes: 1
Views: 643
Reputation: 903
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") %>
Upvotes: 1
Reputation: 1038760
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!" });
Upvotes: 1
Reputation: 1062745
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
Upvotes: 2