我在这里遇到了问题,希望有人能帮我解决问题。问题是:即时通讯使用c#和mvc。我想将db表传递给另一个函数。我不知道如何解决这个问题。希望那里有人可以帮助我
public ActionResult Index()
{
var viewModel = db.test.ToList()
ExportExcel(viewModel); //pass current table to excel to export
return View(viewModel);
}
//export to excel
public ActionResult ExportExcel(xxxx viewModel)
{
var grid = new GridView();
grid.DataSource = from p in viewModel
select new
{
Name = p.name,
No = p.staffno
};
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View("MyView");
}
答案 0 :(得分:0)
将ExportExcel函数返回类型更改为bool或void,并将参数更改为viewmodel而不是xxxx .. 您可以将该代码移动到某个实用程序类。
答案 1 :(得分:0)
由于View("viewName")
会返回一个查看结果,您可以直接调用它并从Index方法返回它,前提是您将viewModel传递给ExportExcel
方法。
public ActionResult Index()
{
var viewModel = db.test.ToList()
var viewResult = ExportExcel(viewModel);
return viewResult;
}
//export to excel
public ActionResult ExportExcel(List<test> viewModel)
{
var grid = new GridView();
grid.DataSource = from p in viewModel
select new
{
Name = p.name,
No = p.staffno
};
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View("MyView");
}
答案 2 :(得分:0)
假设viewModel是System.Data.DataTable:
public ActionResult Index()
{
// Dummy data
var dt = new DataTable();
dt.Columns.Add("id", typeof(int));
var row = dt.NewRow();
row[0] = 4;
dt.Rows.Add(row);
ExportExcel(dt);
return View();
}
在导出方法中,将参数类型更改为DataTable:
public EmptyResult ExportExcel(DataTable test)
{
var grid = new GridView();
grid.DataSource = test;
grid.DataBind();
... your existing code
return new EmptyResult();
}