I am a coding beginner and I try to use MVC to built an employees management system, here are my simplified code:
model
public class Employee
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set;}
}
I have a textbox in Index View so that I could input some words to filter employee list.
public async Task<IActionResult> Index( string? searchString )
{
var employees = from e in _context.Employee select e;
if (!searchString.IsNullOrEmpty())
{
employees = employees.Where(w => w.FirstName.Contains(searchString));
}
return View(employees)
}
Now I wish to export the list to Excel, so I wrote an IActionResult ExportToExcel()
to do the job and put an button in Index View to trigger it.
But I don't know how to pass the data employees
to action ExoirtToExcel()
, I tested to export Excel without data and the action works fine.
I tried use TempData to storage data employees
...
if (!searchString.IsNullOrEmpty())
{
employees = employees.Where(w => w.FirstName.Contains(searchString));
}
TempData["Employees"] = employees;
return View(employees)
but got an exception 'Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer' cannot serialize an object of type
Is there anyway I can pass the data employees
from Index action to another ?
Every advice will be appreciated.