1

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

1 Answer 1

2

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";)

Sign up to request clarification or add additional context in comments.

6 Comments

my problem here is that i have Views/Reports using Generic List w/ jquery datatables that has a lot of filters where i really need to use my Model/Entitities as paramerters..thanks
@BizApps, not sure what is implied relation between using parameters and ajax method? See $.param for serializing your js object into url-encoded data. AFAIK, default model binder in ASP.NET MVC side should able to convert query string values to your model/entity parameter.
thanks @VinayC , i will just try to concatenate the values of all my filter and split it on my code on controller thanks.
I also have the same issue like BizApps. VinayC's solution worked with the limitation where my filter has long query string and I run out of maxQueryString. To solve that by making an ajax POST call to controller actionmethod that takes the filter parameters and async=false to save the filter in the session variable. After this call is returned successfully, simply do document.location with the actionmethod where read the session variable that contains filter and perform export. Just wanted to share my way, JIC it helps someone.
@peacefulmember, that is one way to do it with POST request - a better variation would involve creating random key (say guid) and push parameters into the cache with small expiry time (5-10 minutes) and return the key as POST result. Subsequent GET would use the key as query parameter. Yet another way of doing is to use new window and do normal POST (form.submit) from that window to get excel file.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.