I know there are several solutions out there, but I was looking for a pure C# solution. I like @TylerLong's solution the best, though I wanted to support multiple messages for each type. Plus, this is updated for ASP.NET MVC4, and being that there are no config file changes necessary, it would probably work for other versions of the MVC framework as well.
Features
- Pure C# solution
- Uses view helpers, partials and an extension method to the Controller class
- Should be compatible with multiple versions of the MVC framework
- Supports multiple messages per type
- No config changes to your Web.config files
1) Create MvcProject/Helpers/FlashHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcProject.Helpers
{
public enum FlashLevel
{
Info = 1,
Success = 2,
Warning = 3,
Danger = 4
}
public static class FlashHelper
{
public static void Flash(this Controller controller, string message, FlashLevel level)
{
IList<string> messages = null;
string key = String.Format("flash-{0}", level.ToString().ToLower());
messages = (controller.TempData.ContainsKey(key))
? (IList<string>)controller.TempData[key]
: new List<string>();
messages.Add(message);
controller.TempData[key] = messages;
}
}
}
2) Create MvcProject/Views/Shared/_Flash.cshtml
as a Partial:
@helper FlashMessage(System.Web.Mvc.TempDataDictionary tempData)
{
<div class="flash-messages">
@foreach (FlashLevel level in (FlashLevel[]) Enum.GetValues(typeof(FlashLevel)))
{
string type = level.ToString().ToLower();
string key = "flash-" + type;
if (tempData.ContainsKey(key))
{
IList<string> messages = (IList<string>)tempData[key];
foreach (string message in messages)
{
<p class="alert alert-@type" role="alert">@message</p>
}
}
}
</div>
}
@FlashMessage(TempData)
3) Render the _Flash
partial in MvcProject/Views/Shared/_Layout.cshtml
@Html.Partial("_Flash")
This will cause the flash messages to be included in the web page.
4) Add flash messages in your Controllers
The last piece of the puzzle is in your Controllers, which should now have a method called Flash(string message, FlashLevel level)
:
using MvcProject.Helpers;
public class FoosController : Controller
{
public ActionResult Edit(int id, FooViewModel model)
{
// ...
this.Flash("Foo was updated", FlashLevel.Success);
this.Flash("Another success message!", FlashLevel.Success);
this.Flash("But there was a slight problem...", FlashLevel.Warning);
return RedirectToAction("Edit", new { id = id });
}
}