Show a message after redirecting after a successful POST request without using TempData

Viewed 1509

I am using the Post-Redirect-Get pattern. In my asp.net core MVC web app, this is what happens:

  1. User submits a form via POST which adds an item to db.
  2. Controller adds the new item and redirects with 302/303 to "/Home/Index/xxxx", where xxxx is the id of the item.
  3. The new request (/Home/Index/xxxx) is served by the controller, and it displays the item. And the item url in the address bar is something the user can copy and share.

At step 3 above, I would like to show the user a message saying "Item was successfully added".

This is my code (without the success message):

public async Task<IActionResult> Index(string id)
{
    ItemView itemView = null;
    if (string.IsNullOrEmpty(id))
        itemView = new ItemView();  // Create an empty item.
    else
        itemView = await itemService.GetItemAsync(id);
    return View(itemView);
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ItemView itemView)
{
    string id = await itemService.AddItemAsync(itemView);
    return RedirectToAction("Index", "Home", new { id = id });
}

There are few ways to do this that I found in other answers on stackoverflow.

  1. Redirect to "/Home/Index/xxxx?success=true". When action sees a success=true param, it can display the success message. But I don't want to use an extra param because I would like users to be able to just copy the url from the address bar and share it. And I don't want them sharing the url that has success param, because then everyone who clicks on the shared link will see the message "Item was successfully added".
  2. This post suggests using TempData, which is a good solution. I think that would need me to enable sticky behavior on the server, which I would like to avoid if possible.
  3. I can probably use referrer url to determine if the request came after a form submission, and in that case I can show the message.
1 Answers
Related