What is the recommended approach to providing user notifications / confirmations in MVC?

こ雲淡風輕ζ 提交于 2019-11-30 04:07:52
Darin Dimitrov

I like option 1. Also you don't need conditions and it works with javascript disabled. Just stick it somewhere in the masterpage and it should be OK:

<div class="notification">
    <%= Html.Encode(TempData["Notification"]) %>
</div>

You could of course progressively enhance/animate this by using some nice plugin such as jGrowl or Gritter or even look at how StackOverflow does it.

Another solution is to write a helper which is probably the neatest:

public static class HtmlExtensions
{
    public static MvcHtmlString Notification(this HtmlHelper htmlHelper)
    {
        // Look first in ViewData
        var notification = htmlHelper.ViewData["Notification"] as string;
        if (string.IsNullOrEmpty(notification))
        {
            // Not found in ViewData, try TempData
            notification = htmlHelper.ViewContext.TempData["notification"] as string;
        }

        // You may continue searching for a notification in Session, Request, ... if you will

        if (string.IsNullOrEmpty(notification))
        {
            // no notification found
            return MvcHtmlString.Empty;
        }

        return FormatNotification(notification);
    }

    private static MvcHtmlString FormatNotification(string message)
    {
        var div = new TagBuilder("div");
        div.AddCssClass("notification");
        div.SetInnerText(message);
        return MvcHtmlString.Create(div.ToString());
    }

}

And then in your master:

<%= Html.Notification() %>

For general notification stuff, I usually create a partial view to hide the ugly conditional code, and include it on my master layout.

So, in an appropriate place in the master:

<% Html.RenderPartial("_Notifications") %>

And in a partial view:

<% if(TempData["UserNotification"] != null {%>
    <div class="notification">Thanks for your Feedback&#33;</div>
<% } %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!