We had a new requirement in a project: We need to display a message to the users after they did some kind of action, but that message needed to disappear before the next request. We tried to do this using Session, but that didn't work out very well; after all, there's another construct we can use that does exactly this kind of thing: TempData.

TempData originally (MVC1) only stored the data until the next request, but as of MVC2 it now stores the data until you read it or until the completion of the next request, whichever is first.

But, of course, I wanted our solution to be a little more flexible that just having a bunch of FlashMessage[] checks all over my views and controllers. So, I now present to you: FlashMessage.

A bolt of lightning

Here's the parts.

First, there's an Enum for the types of message we can display:

public Enum FlashMessageType

Now, we want this be set on the controller files, all of them. So, let's make a ControllerBase class:

public class ControllerBase : Controller
    public void SetFlash(FlashMessageType type, string text)
        TempData["FlashMessage.Type"] = type;
        TempData["FlashMessage.Text"] = text;

And have all the other controllers inherit from it.

But we still need to display the message. So, let's make a new partial view, FlashMessage.cshtml:

    string text = (string)TempData["FlashMessage.Text"];
    string cssClass = null;
    if (!string.IsNullOrWhiteSpace(text))
        FlashMessageType type = (FlashMessageType)TempData["FlashMessage.Type"];
        cssClass = type.ToString().ToLower();
@if (!string.IsNullOrWhiteSpace(text))
    <div class="@cssClass">

Now we can just call this on our main view like @Html.Partial("FlashMessage").

Finally, we set the message on the controller:

public class HomeController : ControllerBase
    public ActionResult Index()
        HomeIndexVM model = new HomeIndexVM();
        return View(model);

    public ActionResult Index(HomeIndexVM model)
        SetFlash(model.Type, model.Message);
        return RedirectToAction("Index");

And now we have a scalable, extensible Flash Message for our use anywhere in this project!

Grab the code from GitHub, and feel free to extend this however you like.

Happy Coding!