patterncsharpMinor
Storing Temporal Message Lists in ASP.NET MVC TempData
Viewed 0 times
temporaltempdatamvcmessagenetlistsstoringasp
Problem
I've been using the following the code to store temporal error messages in
The controller helper code:
Example Use:
Here is the rendering code:
Can you spot any issues?
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 messages = controller.TempData["Messages"] as List ?? new List();
messages.Add(message);
controller.TempData["Messages"] = messages;
}
public static void SetErrorMessage(this ControllerBase controller, string errorMessage)
{
List messages = controller.TempData["ErrorMessages"] as List ?? new List();
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:
Error Messages
)
{
%>
Messages
)
{
%>Can you spot any issues?
Solution
On the whole the approach is fine, but do not use
Therefore, if you're looking to put something in place which allows developers to push messages into your views easily, you need to expose the ability to put data in either
Another option is to clear the
As a final point, your function names
I would assume that my message is now set to "Bar", but behind the scenes it's a list with both "Foo" and "Bar". I'd recommend changing your function names to
TempData unless you're looking to populate this information across redirects. TempData comes with a host of issues, and its behaviour isn't quite what you think.ViewData, on the other hand, is designed exactly for this purpose but comes with the caveat that it doesn't persist across redirects.Therefore, if you're looking to put something in place which allows developers to push messages into your views easily, you need to expose the ability to put data in either
ViewData or TempData, depending on whether they want to redirect or not.Another option is to clear the
TempData entry manually after the call has finished, but I wouldn't recommend this approach.As a final point, your function names
SetMessage and SetErrorMessage are misleading in that they imply you've got one spot only for the message. To me, as a user of your function, when doing this:this.SetMessage("Foo");
this.SetMessage("Bar");I would assume that my message is now set to "Bar", but behind the scenes it's a list with both "Foo" and "Bar". I'd recommend changing your function names to
AddMessage and AddErrorMessage instead, which implies that behind the scenes there is a collection of elements.Code Snippets
this.SetMessage("Foo");
this.SetMessage("Bar");Context
StackExchange Code Review Q#1926, answer score: 5
Revisions (0)
No revisions yet.