I have an HTML form that allows users to fill out a bunch of different parameters, and then it will display the result on the same page via an AJAX call. Pretty standard, and it works great. I had a request to allow for exporting the data in Excel format. Unfortunately, just returning a File ActionResult won't work from within the context of an Ajax form. There were some workaround posted out there (e.g. hidden iframe, duplicate the form on the page, etc.). I found the following approach to be a nice compromise and DRYs things up considerably. The key is that by putting the onclick on the Export button to do this.form.submit(), it forces the request to be a standard POST and not an AJAX call.
View.cshtml
@using(Ajax.BeginForm("ReportData", new AjaxOptions {UpdateTargetId="result"})) {
... other input elements here
<input type="submit" value="Display" />
<input type="submit" value="Export" onclick="this.form.submit();">
}
Controller.cs
public ActionResult ReportData(... parameters go here ...) {
if (Request.IsAjaxRequest()) {
// Do the normal behavior here to build up a string
return Content(s);
}
// I actually stream the result with a custom ExcelResult action,
// but this shows how to just return a file.
return File(@"c:\library\report.xls", "application/vnd.ms-excel");
}