Thoughts from Dan Miser RSS 2.0
# Sunday, February 19, 2012
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");
}
Sunday, February 19, 2012 5:33:35 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
ASP.NET MVC
Navigation
Archive
<November 2014>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2014
Dan Miser
Sign In
Statistics
Total Posts: 388
This Year: 0
This Month: 0
This Week: 0
Comments: 630
Themes
Pick a theme:
All Content © 2014, Dan Miser
DasBlog theme 'Business' created by Christoph De Baene (delarou)