0

I've got a controller action that is using TempData to get complex objects from another action. The issue happens when the user refreshes the page and gets null object errors on the view. The complex objects are not passed through the URL like the other values are. Is there a way to prevent this from happening? An alternative solution would be to remove all query parameters from the URL on a page refresh and display the view like it was a new object.

Controller

public IActionResult Daily(Daily daily)
{
    new ReportDaily().GetAvailableSavedCriteria(out List<ReportCriteria> reportCriteria, out Notification not);

    if (daily.SelectedCriteria == null) {
        //Create daily report object and initialize the default values
        var newModel = new Daily
        {
            PaymentTypes = DGetPaymentTypes(),
            Users = DGetUsers(),
            Criteria = reportCriteria,
            StartDate = DateTime.Today.Date,
            EndDate = DateTime.Today.Date,
            County = true,
            Municipality = true
        };
        return View(newModel);
    }
    else
    {
        daily.PaymentTypes = TempData.Get<List<Daily.PaymentType>>("PaymentTypes") == null ? DGetPaymentTypes() : TempData.Get<List<Daily.PaymentType>>("PaymentTypes");
        daily.Users = TempData.Get<List<Daily.User>>("Users") == null ? DGetUsers() : TempData.Get<List<Daily.User>>("Users");
        daily.Criteria = reportCriteria;
        return View("Daily", daily);
    }
}
sjohn285
  • 385
  • 5
  • 20
  • 1
    Does this answer your question? [ASP.NET MVC does browser refresh make TempData useless?](https://stackoverflow.com/questions/2642062/asp-net-mvc-does-browser-refresh-make-tempdata-useless) – Owen Pauling Mar 16 '20 at 20:56

1 Answers1

1

TempData only used for a single redirect, to keep the data from another action after refreshing, you can use Session to achieve it.

To use Session in core mvc, you need to add following codes to the starup.cs file:

  • Add services.AddSession(); in ConfigureServices method.
  • Add app.UseSession(); in Configure method.

To save complex object in Session,you can convert the list object into a json format for storage, and then deserialize it into a list object when you get it.

HttpContext.Session.SetString("PaymentTypes", JsonConvert.SerializeObject(pamentTypeList));

Daily Action:

//.....

daily.PaymentTypes = HttpContext.Session.GetString("PaymentTypes") == null ? DGetPaymentTypes() : JsonConvert.DeserializeObject<List<Daily.PaymentType>> (HttpContext.Session.GetString("PaymentTypes"));
LouraQ
  • 6,443
  • 2
  • 6
  • 16