Reputation: 173
Edit 2: One thing I failed to mention is that I was making the post request with an onclick event in jQuery. I removed the jQuery and wrapped the button in a form. I'm guessing it has to do with that, because now it is working as I intended with TempData. If anyone has any insight as to why this is the case, I would love to hear it. Should've thought of it sooner.
Edit: I investigated a little more and noticed that the cookie ".AspNetCore.Mvc.CookieTempDataProvider" is added after the redirect, but is removed after the request is complete. If I go back in the browser and then forward again, the message is shown. I also tried removing TempData altogether, adding an "IsSaved" property to my ViewModel, setting it to true in the save method, and checking for it in the redirect action and view. Again, it recognizes it when it creates the view on redirect, but nothing shows up unless I go back in the browser and then forward again. So at this point I am not sure what my issue is.
I am trying to show a message after a successful post request. When I set a breakpoint in the view where I am checking if the TempData exists, it exists in the TempData object and goes into the if statement, but nothing changes on the page.
This is the controller action that renders the view where the saving is initiated
public async Task<IActionResult> City(double id)
{
var city = await _service.GetCity(id);
var currentWeather = await _service.GetCurrentWeather(city.ID);
return View("City", new CityViewModel(city, currentWeather));
}
Here is the post action where I set the TempData and redirect back to the previous action
[HttpPost]
public async Task<IActionResult> SaveCity(double id)
{
var city = await _service.GetCity(id);
var user = User.FindFirst(ClaimTypes.NameIdentifier).Value;
var userCity = new UserCity(user, city.ID);
try
{
var result = await _repo.SaveUserCityAsync(userCity);
TempData["Success"] = "Success";
}
catch (Exception ex)
{
}
return RedirectToAction("City", new { id = id });
}
And here is the portion of the view (with a breakpoint I can see that the temp data exists after redirect).
@if (TempData["Success"] != null)
{
<p>@TempData["Success"]</p>
}
Here are the relevant (as far as I can tell) portions of my startup
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationCookie(options =>
{
});
services.Configure<CookieTempDataProviderOptions>(options => {
options.Cookie.IsEssential = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Upvotes: 3
Views: 344