views:

58

answers:

3

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();
});
+2  A: 

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

Marc Gravell
This didn't work. Same result
KieselguhrKid
Wait I lied, it did work, the problem was twofold, I'll post it in my original question. Thanks!
KieselguhrKid
Also, I noticed that when I do it in-line it works fine, but if I put the code in an external script it doesn't work (same JSON prompt to download) ... any ideas?
KieselguhrKid
Scratch that, I had the ID of my button wrong. Everything's working, I'll leave this thread alone now.
KieselguhrKid
+1  A: 

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!" });
Darin Dimitrov
Tried this and it did nothing
KieselguhrKid
As I said it was an addition to @Marc's post, meaning that after you've applied his suggestion you could generate valid JSON as shown in my post.
Darin Dimitrov
+1  A: 

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") %>
Mahdi
This did not work either (thanks for the ChildActionOnly tip)
KieselguhrKid
Do you have default {controller}/{action}/{id} route in your Global.asax?
Mahdi