Reputation: 6130
Hi i have created export class that converts Gridview to excel file.
See below code:
DownloadFileActionResult Class:
public class DownloadFileActionResult : ActionResult
{
public GridView ExcelGridView { get; set; }
public string fileName { get; set; }
public DownloadFileActionResult(GridView gv, string pFileName)
{
ExcelGridView = gv;
fileName = pFileName;
}
public override void ExecuteResult(ControllerContext context)
{
HttpContext curContext = HttpContext.Current;
curContext.Response.ClearContent();
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ExcelGridView.RenderControl(htw);
curContext.Response.Write(sw.ToString());
curContext.Response.End();
}
}
Jquery-ajax:
function Export(){
var search = {};
search.Name = "MaterialShape";
search.Description = "";
search.Address ="";
var url_ = generateURL("/Home/Download"); //Call Save Controller and pass details entities
$.ajax({
type: "POST",
url: url_,
data: search, //details will act as the Entities Model
traditional: true,
success: function(data) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + XMLHttpRequest.responseText);
},
dataType: 'json'
});
};
Search Parmeter Properties:
public class SearchParams
{
public string Name{ get; set; }
public string Description {get;set;}
public string Address{get;set;}
...
}
And then i implement it on my controller:
//Export to excel
public ActionResult Download(SearchParam param)
{
List<Lookup> lookupList = data.GetLookup(param);
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = lookupList;
grid.DataBind();
return new DownloadFileActionResult(grid, "test");
}
It is working(without search param values) when i type the controller url manually
http://localhost:54928/Home/Download
or using html.action link
<%= Html.ActionLink("Home", "/Download", "Home")%>
but it is not working when i use ajax call
<img src="<%=Url.Content("~/Images/export.png")%>" id="Img1" onclick="Export();" alt="Export" />
that i really need to use.
I am missing something here..any ideas?
Thanks in Regards
Upvotes: 1
Views: 10729
Reputation: 49185
It does not make sense to use $.ajax
to download excel file - the ajax call is really meant to get text-based data (html. xml, JSON) in your js code so that you can work with it. Browser knows how to handle (e.g. prompt for saving the file) the binary content such as excel.
In this case, all you need to is a simple POST/GET request to initiate the excel file download (as simple as document.location = "/home/download?q=keyword";
)
Upvotes: 2