0

Since, Ajax.BeginForm is just a wrapper around jQuery.ajax() call, is there a way to set the dataType property on the underlying ajax() object? In particular I want to set dataType="json" so that it can handle json responses.

Thanks, Roman

Roman Royter
  • 1,655
  • 13
  • 28

1 Answers1

1

It seems that it can (jQuery 1.5.1):

<script type="text/javascript">
    function success(result) {
        alert(result.Bar);
    }
</script>

@using (Ajax.BeginForm("Foo", new AjaxOptions { OnSuccess = "success" }))
{
    <input type="submit" value="OK" />
}

and the action would return JSON:

[HttpPost]
public ActionResult Foo()
{
    return Json(new { Bar = "baz" });
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I guess I'll take that route, but just so you know, in your example you're returning json disguised as text. I bet if you look in fiddler on the response Content-type it will say "text" and not "application/json". If you change the Foo() method to return JsonResult your success function will never be called. But thanks anyway, I guess this workaround will do. – Roman Royter Jul 14 '11 at 14:47
  • @Roman R., I am not sure I understand what you are saying. I already return a `JsonResult` inside my `Foo` action and the `Content-Type` will be set to `application/json`. – Darin Dimitrov Jul 14 '11 at 14:50
  • Maybe I'm wrong but in my example if I change the Foo declaration is public JsonResult Foo() the returned Content-Type is set to application/json and the browser tries to save it (i.e. a dialog pops up with save/open a file) instead of that result being passed to the ajax caller. If this is not the case for you, then I messed up somewhere else. Thanks anyway :) – Roman Royter Jul 14 '11 at 14:55
  • @Roman R., if this happens is probably because you forgot to include the `jquery.unobtrusive-ajax.js` script to your page which unobtrusively AJAXifies all Ajax.* helpers in ASP.NET MVC 3. – Darin Dimitrov Jul 14 '11 at 14:58
  • Darin. No matter what I try, my response always prompts a user to save the JSON return result. I can't get it to do anything else, particularly with the Ajax.BeginForm call – SoftwareSavant Nov 27 '12 at 19:14
  • @DmainEvent, you must have forgotten to include `jquery` and/or `jquery.unobtrusive-ajax` scripts to your page or you have some javascript error. Checkout your javascript debugging console. – Darin Dimitrov Nov 27 '12 at 22:11
  • @DmainEvent, you are not the only one experiencing this problem. Please see http://stackoverflow.com/questions/5388893/ie9-json-data-do-you-want-to-open-or-save-this-file and http://stackoverflow.com/questions/8591998/ie-tries-to-download-json-in-asp-net-mvc-3 for related questions. – John Washam Sep 09 '13 at 21:09