Asp.net mvc 通知面板类似于stackoverflow';s

Asp.net mvc 通知面板类似于stackoverflow';s,asp.net-mvc,Asp.net Mvc,还记得出现在页面顶部的小div通知我们一些事情(比如新的徽章)吗 我也想实现类似的东西,我正在寻找一些最佳实践或模式 我的网站也是一个ASP.NETMVC应用程序。理想情况下,答案应包括“将其放入母版页”和“在控制器中执行此操作”等细节 为了让您不必亲自查看,这是我从stackoverflow未登录时收到的欢迎消息中看到的代码 <div class="notify" style=""> <span> First time at Stack Overflow?

还记得出现在页面顶部的小div通知我们一些事情(比如新的徽章)吗

我也想实现类似的东西,我正在寻找一些最佳实践或模式

我的网站也是一个ASP.NETMVC应用程序。理想情况下,答案应包括“将其放入母版页”和“在控制器中执行此操作”等细节

为了让您不必亲自查看,这是我从stackoverflow未登录时收到的欢迎消息中看到的代码

<div class="notify" style="">
  <span>
    First time at Stack Overflow? Check out the
    <a href="/messages/mark-as-read?returnurl=%2ffaq">FAQ</a>!
  </span>
  <a class="close-notify" onclick="notify.close(true)" title="dismiss this notification">×</a>
</div>

<script type="text/javascript">

  $().ready(function() {
    notify.show();
  });

</script>

第一次出现堆栈溢出?查看
!
×
$().ready(函数()){
notify.show();
});
我想补充一点,我完全理解这一点,也理解jquery的参与。我只对谁将代码放入标记以及何时(“谁”是指ASP.NET MVC应用程序中的哪些实体)感兴趣


谢谢

虽然这些都不是官方的,但我遵循的常见做法会导致如下结果:

  • 创建将在标记中充当通知容器的元素,但默认情况下将其隐藏(这可以通过多种方式完成-JavaScript、外部CSS或内联样式)
  • 让脚本负责标记外部的通知行为。在上面的示例中,您可以看到有一个
    onclick
    以及另一个函数,该函数在标记中包含的页面加载时触发。虽然它是有效的,但我认为这是表达和行为的混合
  • 将通知消息的表示形式保留在外部样式表中
同样,这些只是我在你的问题中提到的常见做法。正如你问题的本质已经表明的那样,web开发的问题是,有很多方法可以用相同的结果来做相同的事情。

StackOverflow使用了—你在so发布的JS代码是一个jQuery调用。它几乎不需要任何代码就可以完全满足您的需求。强烈推荐。

有完整的解决方案

复制粘贴:

这是标记,最初是隐藏的,以便我们可以淡入:

<div id='message' style="display: none;">
    <span>Hey, This is my Message.</span>
    <a href="#" class="close-notify">X</a>
</div>
这是javascript(使用jQuery):

瞧。根据您的页面设置,您可能还需要在屏幕顶部编辑正文页边距


.

我看到以下jQuery函数了吗?我相信这会将html注入id为notify的div容器中

我不明白基于某些事件如何使用和调用这个JS,也许有人可以解释一下

var notify = function() {
var d = false;
var e = 0;
var c = -1;
var f = "m";
var a = function(h) {
    if (!d) {
        $("#notify-container").append('<table id="notify-table"></table>');
        d = true
    }
    var g = "<tr" + (h.messageTypeId ? ' id="notify-' + h.messageTypeId + '"' : "");
    g += ' class="notify" style="display:none"><td class="notify">' + h.text;
    if (h.showProfile) {
        var i = escape("/users/" + h.userId);
        g += ' See your <a href="/messages/mark-as-read?messagetypeid=' + h.messageTypeId + "&returnurl=" + i + '">profile</a>.'
    }
    g += '</td><td class="notify-close"><a title="dismiss this notification" onclick="notify.close(';
    g += (h.messageTypeId ? h.messageTypeId : "") + ')">&times;</a></td></tr>';
    $("#notify-table").append(g)
};
var b = function() {
    $.cookie("m", "-1", {
        expires: 90,
        path: "/"
    })
};
return {
    showFirstTime: function() {
        if ($.cookie("new")) {
            $.cookie("new", "0", {
                expires: -1,
                path: "/"
            });
            b()
        }
        if ($.cookie("m")) {
            return
        }
        $("body").css("margin-top", "2.5em");
        a({
            messageTypeId: c,
            text: 'First time here? Check out the <a onclick="notify.closeFirstTime()">FAQ</a>!'
        });
        $(".notify").fadeIn("slow")
    },
    showMessages: function(g) {
        for (var h = 0; h < g.length; h++) {
            a(g[h])
        }
        $(".notify").fadeIn("slow");
        e = g.length
    },
    show: function(g) {
        $("body").css("margin-top", "2.5em");
        a({
            text: g
        });
        $(".notify").fadeIn("slow")
    },
    close: function(g) {
        var i;
        var h = 0;
        if (g && g != c) {
            $.post("/messages/mark-as-read", {
                messagetypeid: g
            });
            i = $("#notify-" + g);
            if (e > 1) {
                h = parseInt($("body").css("margin-top").match(/\d+/));
                h = h - (h / e)
            }
        } else {
            if (g && g == c) {
                b()
            }
            i = $(".notify")
        }
        i.children("td").css("border-bottom", "none").end().fadeOut("fast", function() {
            $("body").css("margin-top", h + "px");
            i.remove()
        })
    },
    closeFirstTime: function() {
        b();
        document.location = "/faq"
    }
 }
} ();
var notify=function(){
var d=假;
var e=0;
var c=-1;
var f=“m”;
var a=函数(h){
如果(!d){
$(“#通知容器”)。附加(“”);
d=真
}

var g=“在对代码进行了一点窥探之后,下面是一个猜测:

以下通知容器始终位于视图标记中:

<div id="notify-container"> </div>

默认情况下,该通知容器是隐藏的,并且在特定情况下由javascript填充。它可以包含任意数量的消息

如果用户未登录

持久性:Cookies用于跟踪消息是否显示

视图中服务器端生成的代码: 我认为如果您未登录,stackoverflow只显示一条消息。以下代码被注入到视图中:

<script type="text/javascript">
    $(function() { notify.showFirstTime(); });
</script>

$(函数(){notify.showFirstTime();});
showFirstTime()javascript方法只是根据是否设置了cookie来确定是否显示“这是您第一次来这里吗?”消息。如果没有cookie,则显示消息。如果用户采取了操作,则设置了cookie,并且将来不会显示消息。nofity.showFirstTime()函数处理cookie的检查

如果用户已登录

持久性:数据库用于跟踪消息是否已显示

视图中服务器端生成的代码: 当请求页面时,服务器端代码检查数据库以查看需要显示哪些消息。然后,服务器端代码将json格式的消息注入视图,并对showMessages()进行javascript调用

例如,如果我登录到视图,我会在SO的标记中看到以下内容:

    <script type="text/javascript">
1
2 var msgArray = [{"id":49611,"messageTypeId":8,"text":"Welcome to Super User! Visit your \u003ca href=\"/users/00000?tab=accounts\"\u003eaccounts tab\u003c/a\u003e to associate with our other websites!","userId":00000,"showProfile":false}];
3 $(function() { notify.showMessages(msgArray); });
4
</script>

1.
2 var msgArray=[{“id”:49611,“messageTypeId”:8,“text:“欢迎使用超级用户!访问您的\u003ca href=\”/users/00000?tab=accounts\“\u003eaccounts tab\u003c/a\u003e以与我们的其他网站关联!”,“userId”:00000,“showProfile”:false}];
3$(函数(){notify.showMessages(msgArray);});
4.
因此,如果用户未登录,服务器端代码要么注入代码以调用“showFirstTime”方法,要么注入消息并调用登录用户的“showMessages”

有关客户端代码的更多信息

另一个关键组件是Picflight已经缩小的“notify”JavaScript模块(您可以使用firebug的yslow进行同样的操作)。notify模块根据服务器端生成的JavaScript处理通知div的填充

未登录,客户端

如果用户未登录,则当用户X发出通知或通过创建cookie转到FAQ时,模块将处理事件。它还通过检查cookie来确定是否显示首次消息

已登录,客户端


如果用户登录,notify模块会将服务器生成的所有消息添加到notification div中。当用户拒绝消息时,它也很可能使用ajax来更新数据库。

我编写了这段Javascript,它只做这项工作,包括堆叠,并像Stack Overflow的那样在滚动时与您保持一致每当添加新条时,将整个页面向下推。这些条也会过期。这些条也会滑入存在状态

// Show a message bar at the top of the screen to tell the user that something is going on.
// hideAfterMS - Optional argument. When supplied it hides the bar after a set number of milliseconds.
    function AdvancedMessageBar(hideAfterMS) {
        // Add an element to the top of the page to hold all of these bars.
        if ($('#barNotificationContainer').length == 0) 
        {               

        var barContainer = $('<div id="barNotificationContainer" style="width: 100%; margin: 0px; padding: 0px;"></div>');
        barContainer.prependTo('body');

        var barContainerFixed = $('<div id="barNotificationContainerFixed" style="width: 100%; position: fixed; top: 0; left: 0;"></div>');
        barContainerFixed.prependTo('body');
    }

    this.barTopOfPage = $('<div style="margin: 0px; background: orange; width: 100%; text-align: center; display: none; font-size: 15px; font-weight: bold; border-bottom-style: solid; border-bottom-color: darkorange;"><table style="width: 100%; padding: 5px;" cellpadding="0" cellspacing="0"><tr><td style="width: 20%; font-size: 10px; font-weight: normal;" class="leftMessage" ></td><td style="width: 60%; text-align: center;" class="messageCell"></td><td class="rightMessage" style="width: 20%; font-size: 10px; font-weight: normal;"></td></tr></table></div>');
    this.barTopOfScreen = this.barTopOfPage.clone();

    this.barTopOfPage.css("background", "transparent");
    this.barTopOfPage.css("border-bottom-color", "transparent");
    this.barTopOfPage.css("color", "transparent");

    this.barTopOfPage.prependTo('#barNotificationContainer');
    this.barTopOfScreen.appendTo('#barNotificationContainerFixed');


    this.setBarColor = function (backgroundColor, borderColor) {     

        this.barTopOfScreen.css("background", backgroundColor);
        this.barTopOfScreen.css("border-bottom-color", borderColor);
    };

    // Sets the message in the center of the screen.
    // leftMesage - optional
    // rightMessage - optional
    this.setMessage = function (message, leftMessage, rightMessage) {
        this.barTopOfPage.find('.messageCell').html(message);
        this.barTopOfPage.find('.leftMessage').html(leftMessage);
        this.barTopOfPage.find('.rightMessage').html(rightMessage);

        this.barTopOfScreen.find('.messageCell').html(message);
        this.barTopOfScreen.find('.leftMessage').html(leftMessage);
        this.barTopOfScreen.find('.rightMessage').html(rightMessage);
    };


    this.show = function() {
        this.barTopOfPage.slideDown(1000);
        this.barTopOfScreen.slideDown(1000);
    };

    this.hide = function () {
        this.barTopOfPage.slideUp(1000);
        this.barTopOfScreen.slideUp(1000);
    };

    var self = this;   


    if (hideAfterMS != undefined) {
        setTimeout(function () { self.hide(); }, hideAfterMS);
    }    
}
如果你想把这些叠起来,那么jus
    <script type="text/javascript">
1
2 var msgArray = [{"id":49611,"messageTypeId":8,"text":"Welcome to Super User! Visit your \u003ca href=\"/users/00000?tab=accounts\"\u003eaccounts tab\u003c/a\u003e to associate with our other websites!","userId":00000,"showProfile":false}];
3 $(function() { notify.showMessages(msgArray); });
4
</script>
// Show a message bar at the top of the screen to tell the user that something is going on.
// hideAfterMS - Optional argument. When supplied it hides the bar after a set number of milliseconds.
    function AdvancedMessageBar(hideAfterMS) {
        // Add an element to the top of the page to hold all of these bars.
        if ($('#barNotificationContainer').length == 0) 
        {               

        var barContainer = $('<div id="barNotificationContainer" style="width: 100%; margin: 0px; padding: 0px;"></div>');
        barContainer.prependTo('body');

        var barContainerFixed = $('<div id="barNotificationContainerFixed" style="width: 100%; position: fixed; top: 0; left: 0;"></div>');
        barContainerFixed.prependTo('body');
    }

    this.barTopOfPage = $('<div style="margin: 0px; background: orange; width: 100%; text-align: center; display: none; font-size: 15px; font-weight: bold; border-bottom-style: solid; border-bottom-color: darkorange;"><table style="width: 100%; padding: 5px;" cellpadding="0" cellspacing="0"><tr><td style="width: 20%; font-size: 10px; font-weight: normal;" class="leftMessage" ></td><td style="width: 60%; text-align: center;" class="messageCell"></td><td class="rightMessage" style="width: 20%; font-size: 10px; font-weight: normal;"></td></tr></table></div>');
    this.barTopOfScreen = this.barTopOfPage.clone();

    this.barTopOfPage.css("background", "transparent");
    this.barTopOfPage.css("border-bottom-color", "transparent");
    this.barTopOfPage.css("color", "transparent");

    this.barTopOfPage.prependTo('#barNotificationContainer');
    this.barTopOfScreen.appendTo('#barNotificationContainerFixed');


    this.setBarColor = function (backgroundColor, borderColor) {     

        this.barTopOfScreen.css("background", backgroundColor);
        this.barTopOfScreen.css("border-bottom-color", borderColor);
    };

    // Sets the message in the center of the screen.
    // leftMesage - optional
    // rightMessage - optional
    this.setMessage = function (message, leftMessage, rightMessage) {
        this.barTopOfPage.find('.messageCell').html(message);
        this.barTopOfPage.find('.leftMessage').html(leftMessage);
        this.barTopOfPage.find('.rightMessage').html(rightMessage);

        this.barTopOfScreen.find('.messageCell').html(message);
        this.barTopOfScreen.find('.leftMessage').html(leftMessage);
        this.barTopOfScreen.find('.rightMessage').html(rightMessage);
    };


    this.show = function() {
        this.barTopOfPage.slideDown(1000);
        this.barTopOfScreen.slideDown(1000);
    };

    this.hide = function () {
        this.barTopOfPage.slideUp(1000);
        this.barTopOfScreen.slideUp(1000);
    };

    var self = this;   


    if (hideAfterMS != undefined) {
        setTimeout(function () { self.hide(); }, hideAfterMS);
    }    
}
var mBar = new AdvancedMessageBar(10000);
mBar.setMessage('This is my message', 'Left Message', 'Right Message');
mBar.show();