I've been using the following the code to store temporal error messages in TempData
, to be displayed from my master page on production sites without any problems, but is this a good way of doing it?
The controller helper code:
namespace System.Web.Mvc
{
public static class Controllers
{
public static void SetMessage(this ControllerBase controller, string message)
{
List<string> messages = controller.TempData["Messages"] as List<string> ?? new List<string>();
messages.Add(message);
controller.TempData["Messages"] = messages;
}
public static void SetErrorMessage(this ControllerBase controller, string errorMessage)
{
List<string> messages = controller.TempData["ErrorMessages"] as List<string> ?? new List<string>();
messages.Add(errorMessage);
controller.TempData["ErrorMessages"] = messages;
}
}
}
Example Use:
public ActionResult Edit()
{
// .. do stuff
this.SetMessage("You edited X.");
return View();
}
Here is the rendering code:
<%
if (TempData["ErrorMessages"] != null)
{
%>
Error Messages
<%
foreach (string s in TempData["ErrorMessages"] as List<string>)
{
%><%=s%><%
}
}
if (TempData["Messages"] != null)
{
%>
Messages
<%
foreach (string s in TempData["Messages"] as List<string>)
{
%><%=s%><%
}
}
%>
Can you spot any issues?