There is a feature called \'flash\' in ruby on rails where you can put a message in \'flash\', redirect, and the message is available in the next action.
Example of
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.
MvcProject/Helpers/FlashHelper.csusing 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 messages = null;
string key = String.Format("flash-{0}", level.ToString().ToLower());
messages = (controller.TempData.ContainsKey(key))
? (IList)controller.TempData[key]
: new List();
messages.Add(message);
controller.TempData[key] = messages;
}
}
}
MvcProject/Views/Shared/_Flash.cshtml as a Partial:@helper FlashMessage(System.Web.Mvc.TempDataDictionary tempData)
{
}
@FlashMessage(TempData)
_Flash partial in MvcProject/Views/Shared/_Layout.cshtml@Html.Partial("_Flash")
This will cause the flash messages to be included in the web page.
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 });
}
}