0

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.

Lukeric
  • 1
  • 2
  • You are trying to store a complex object list in your TempData. Please see the link : https://stackoverflow.com/questions/34638823/store-complex-object-in-tempdata – SoftwareDveloper Apr 04 '23 at 20:54
  • @Lukeric which type of data you want to expect json or whole empyee you pass? – Rahul Patil Apr 05 '23 at 06:24
  • @Lukeric use this one ```List employees = new List();``` then after use the list object in foreachloop and add that list object in excel file – Rahul Patil Apr 05 '23 at 06:33
  • @ Rahul Patil my data storages in sql data-base, I wish I could export the object "employees" which have been queried in Index action, not to query again in export action. @ SoftwareDveloper thank you , I will check the link. – Lukeric Apr 06 '23 at 08:00

0 Answers0