private member in controller returns null after be

2020-05-03 11:55发布

问题:

I have a controller in ASP.NET MVC application.

private GipDbContext db = new GipDbContext();
private Employee employeeObj;

public ActionResult Edit(int? id)
        {
            Employee employee = db.Employees.Find(id);

            //employeeObj SET TO ANOTHER OBJECT
            employeeObj = employee;

            return View(employee);
        }

public PartialViewResult TimeSeriesData(int? tsdataid)
        {
            TimeSeriesData tsobject = new TimeSeriesData();

            // employeeObj RETURNING NULL
            foreach (var item in employeeObj.TimeSeriesData){
                if (item.TimeSeriesDataID == tsdataid)
                {
                    tsobject = item;
                    break;
                }
            }

The first method being called is Edit, then when TimeSeriesData is called employeeObj is returning null, even though it was set in the Edit method.. any ideas why?

回答1:

Controllers are instantiated for each request. Once you request TimeSeriesData, the controller that was created for the request to Edit has already been disposed. If you need to hold on to a piece of data between requests, you must either put it in Session or TempData (both of which use sessions).