I want to display in my view some message when some user is added.
When something goes wrong in our model, there is a method
TempData isn't a bad way to hand one-offs to the UI for the purposes of notifying the user. The great part about them is they persist between action calls, but are removed once they're read. So, in the case of just handing off a "it worked" message, it works great.
You can tie them in several ways, but I'll give you a general example to get you going:
public static class NotificationExtensions
{
private const String NotificationsKey = "MyApp.Notifications";
public static void AddNotification(this ControllerBase controller, String message)
{
ICollection messages = controller.TempData[NotificationsKey] as ICollection;
if (messages == null)
{
controller.TempData[NotificationsKey] = (messages = new HashSet());
}
messages.Add(message);
}
public static IEnumerable GetNotifications(this HtmlHelper htmlHelper)
{
return htmlHelper.ViewContext.Controller.TempData[NotificationsKey] as ICollection ?? new HashSet();
}
}
Now in your action you can call this.AddNotification("User successfully added!"); and within your view you can display them using:
@foreach (String notification in Html.GetNotifications())
{
@notification/p>
}
(...Or something similar) which could be effectively placed in your main view and used as a general notification method for any action performed. (Almost like how StackOverflow has the gold bar at the top of the page during certain events).