I have following controller. When i search for a specific grade i get a list. What i want is to export this result to excel. I have my export button works fine. But the only thing is that it tries to export everything in db to excel when i click on it. What i want is to export only the results. Any idea?
public ActionResult Index(string searchBy, string search)
{
if (!String.IsNullOrEmpty(searchBy) && !String.IsNullOrEmpty(search))
{
if (searchBy == "ID")
{
return View(db.students.Where(x => x.id==search).ToList());
}
else if (searchBy == "grade")
{
return View(db.students.Where(x => x.grade == search).ToList());
}
else
{
return View(db.students.Take(0));
}
}
public ActionResult ExportData()
{
GridView gv = new GridView();
gv.DataSource = db.students.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=students.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Home");
}
And this is the part in my index view:
@using (Html.BeginForm("ExportData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td></td>
<td>
<input type="submit" name="Export" id="Export" value="Export" />
</td>
</tr>
</table>
}