Success message from Controller to View

前端 未结 6 1428
情歌与酒
情歌与酒 2020-12-30 05:05

The goal

I want to display in my view some message when some user is added.

The problem

When something goes wrong in our model, there is a method

6条回答
  •  再見小時候
    2020-12-30 05:10

    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).

提交回复
热议问题