I am trying to achieve a simple thing in Asp.Net Core. This would have been no big deal in Asp.Net Mvc. I have an action method like this
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,Email,PhoneNo")] Customer customer)
{
if (ModelState.IsValid)
{
_context.Add(customer);
await _context.SaveChangesAsync();
TempData["CustomerDetails"] = customer;
return RedirectToAction("Registered");
}
return View(customer);
}
public IActionResult Registered()
{
Customer customer = (Customer)TempData["CustomerDetails"];
return View(customer);
}
At first I assumed TempData works by default but later realized that it has to be added and configured. I added ITempDataProvider in startup. The official document seems to describe that this should be enough. It didn't work. Then I also configured it to use Session
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
services.AddSession(
options => options.IdleTimeout= TimeSpan.FromMinutes(30)
);
services.AddMvc();
services.AddSingleton<ITempDataProvider,CookieTempDataProvider>();
}
I the following line related to Session in Configure method of Startup before writing app.UseMvc.
app.UseSession();
This still is not working. What is happening is I am not getting any exception because of use of TempData anymore which I got before when I missed some of the configuration but now the create action method is not able to redirect to Registered Method. Create method does all the work but RedirectToAction has no effect. If I remove the line that is assigning Customer details to TempData, the RedirectToAction successfully redirects to that action method. However in this case Registered action method don't have access to CustomerDetails obviously. What am I missing?
@Win. You were right. I realized the serialization, deserialization is required whenever you want to use TempData in Asp.net Core after reading the disclaimer in this article.
https://andrewlock.net/post-redirect-get-using-tempdata-in-asp-net-core/
I first tried to use BinaryFormatter but discovered that it has also been removed from .NET Core. Then I used NewtonSoft.Json to serialize and deserialize.
TempData["CustomerDetails"] = JsonConvert.SerializeObject(customer);
public IActionResult Registered()
{
Customer customer = JsonConvert.DeserializeObject<Customer>(TempData["CustomerDetails"].ToString());
return View(customer);
}
That's the extra work we have to do now but looks like that's how it is now.
来源:https://stackoverflow.com/questions/42978179/not-able-to-redirect-to-action-when-using-tempdata-in-asp-net-core