mvc

Displaying messages from one action on the view of another

Displaying messages from one action on the view of another,display a message
Share it:
After my last post about why you should use the POST, redirect, GET design pattern I got an email asking how you can display a message from one action on the view returned by another. This person wanted to display a message on the view returned by the GET action indicating that the POST action was successful.


For example: When the user updates a product they POST to /Product/Edit/123 which then redirects them to /Product/Show/123. On /Product/Show/123 you want to show a message saying “Product Updated” so that the user can see that it was updated successfully. The message should only be displayed once and only when you’re being redirected from Edit action.

With ASP.NET MVC you can achieve this painlessly using TempData. TempData works like Session (which it uses by default) except that it only stores the data across one redirect.


The code in your controller will look something like this:

[HttpPost]
public ActionResult Edit(Product p)
{
    // Do something here
 
    // Set the message to be displayed in the view
    TempData["Message"] = "Product Updated";
 
    // Redirect the user to /Product/Show/id
    return RedirectToAction("Show", new { id = p.ID });
}
 
public ActionResult Show(int id)
{
    // Grab the product to show
    Product p = _db.Products.Find(id);
 
    // Render the view
    return View(p);
}

The important thing is that your Show action doesn’t even know that the message is being passed. This means that both Show and Edit are completely self-contained which is exactly how you want your actions to be. You can then access it in the view with a snippet like this:

<% if(TempData.ContainsKey("Message")) { %>
     
<: :="" essage="" tempdata="">
<% } %>

Usually, I will place that onto the master page instead of the individual views. This provides a consistent way for any action to display a message without needing to add it to every view.
Share it:

mvc

Post A Comment:

0 comments: