0

I want to export the Excel sheet of my Razor view table. This code shows the table:

public ActionResult Show(int id)
    {
        IEnumerable<GradeSheetViewModel> model = _repGrade.GetList(id);
        return View(model);
    }

Here is the code for export to Excel function

public ActionResult ExportToExcel()
    {
        var gv = new GridView();
        gv.DataSource = this.Show();
        gv.DataBind();
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=DemoExcel.xls");
        Response.ContentType = "application/ms-excel";
        Response.Charset = "";
        StringWriter objStringWriter = new StringWriter();
        HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
        gv.RenderControl(objHtmlTextWriter);
        Response.Output.Write(objStringWriter.ToString());
        Response.Flush();
        Response.End();
        return View("Index");
    } 

but it gives the error at

gv.DataSource = this.Show();

the error is

no overload for the method Show takes 0 argument

halfer
  • 19,824
  • 17
  • 99
  • 186
jerry
  • 1
  • 3
  • The method Show has one parameter id and you call it without parameter. – Jean-Claude Colette Aug 07 '18 at 21:24
  • how can i call it with parameter inside the function ?? @Jean-ClaudeColette – jerry Aug 07 '18 at 21:25
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Aug 08 '18 at 09:11

1 Answers1

0

DataSource property assignment requires IEnumerable as its source. You need to change Show method to return any objects that implements IEnumerable (e.g. List) and call it with id parameter like this:

// Get list object
public List<GradeSheetViewModel> Show(int id)
{
    return _repGrade.GetList(id);
}

// Controller
public ActionResult ExportToExcel(int id)
{
    var gv = new GridView();
    gv.DataSource = Show(id);

    // other stuff
}

Additional note 1: If you want user to download the file you should return file as FileResult instead of adding Response and returning view:

public ActionResult ExportToExcel(int id)
{
    var gv = new GridView();
    gv.DataSource = Show(id);
    gv.DataBind();

    // save the file and create byte array from stream here

    byte[] byteArrayOfFile = stream.ToArray();

    return File(byteArrayOfFile, "application/vnd.ms-excel", "DemoExcel.xls");
}

Additional note 2: Avoid using webforms server controls like GridView in MVC controller. You can choose one of available alternatives from this issue.

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61