Wednesday, July 8, 2015

Download excel report in MVC

public ActionResult Download(string working)
           // return View();
            ViewBag.Message = "Welcome to Report Generation!";
            Temp cm = new Temp();
            List model = cm.getAll();
            GridView gv = new GridView();
            gv.DataSource = model;
            Session["temp"] = gv;

            if (Session["temp"] != null)
                return new DownloadFileActionResult((GridView)Session["temp"], "temp.xls");
                //Some kind of a result that will indicate that the view has 
                //not been created yet. I would use a Javascript message to do so. 
                return View(model);
            //return View(model);
 public class Temp
        public int id { get; set; }
        public string Name { get; set; }
        public Temp() { }
        Temp(int _id,string _name)
            id = _id;
            Name = _name;
        public List getAll()
            List list = new List();
            list.Add(new Temp(1, "Murli"));
            list.Add(new Temp(3, "Deepak"));
            list.Add(new Temp(5, "Prakash"));
            list.Add(new Temp(7, "Mahandar"));
            return list;

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)

        //Create a response stream to create and write the Excel file
        HttpContext curContext = HttpContext.Current;
        curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        curContext.Response.Charset = "";
        curContext.Response.ContentType = "application/";

        //Convert the rendering of the gridview to a string representation 
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        //Open a memory stream that you can use to write back to the response
        byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
        MemoryStream s = new MemoryStream(byteArray);
        StreamReader sr = new StreamReader(s, Encoding.ASCII);

        //Write the stream back to the response

Use multiple submit button on MVC

Create two submit button inside the form
<form action="index"> <input type="submit" name="submitButton" value="Filter" /> <input type="submit" name="submitButton" value="Download" /> </form>
on the controller action use switch case to target the final action command
public ActionResult Index(StatisticsReport stc, string submitButton) { switch (submitButton) { case "Filter" : break; case "Download": return RedirectToAction("Download", list); } } public ActionResult Download(List list) { return View(); }