ASP.NET MVC5中局部視圖的更新

參考網址:
http://cache.baiducontent.com/c?m=9d78d513d98112ef1eb6c7201a17a7224203c5743ca68344398fce1487231b1f483ca5fd65630705a0d8612244ea5e5c9df067346a1420c0ca95d75784ef8f282d8b26367401864110d713a9dc46529b66cf04&p=c3759a46d6c050eb0be296685208bb&newp=81769a479c8750f708e2977e0e558f231610db2151d4d51f6b82c825d7331b001c3bbfb423271101d4c0796507a94c59eefa3075370923a3dda5c91d9fb4c57479c2632528&user=baidu&fm=sc&query=PartialView+action&qid=ddd15747000eb227&p1=5
https://blog.csdn.net/WuLex/article/details/79017918
https://www.cnblogs.com/hbb0b0/p/5111413.html
https://www.cnblogs.com/whatarey/p/9278151.html
 

我的目標:

在一個頁面上,頂部的一欄信息中,有一個“我的消息”,我希望在它的後面加上新消息個數的標示,比如:“我的消息(5)”,就表示有5條新消息,如果沒有新消息時,就顯示爲“我的消息”

我的工程結構:

使用vs2015嚮導生成的結構,框架類的代碼我有稍做修改,在_Layout.cshtml中有:

<td style="vertical-align:middle;" align="right">
    @Html.Partial("_LoginPartial")
</td>


在 _LoginPartial.cshtml中的登錄分支裏添加一個項“我的消息”,如下:

@{
    string strUserInfo = Html.ActionLink("我的消息", "MyMessage", new { controller = "UserManager" }, new { @id = "myMessageTitle_ihd" }).ToHtmlString();
    <li>@Html.Raw(strUserInfo)</li>
}

這裏最重要的一個就是這個Link的ID:myMessageTitle_ihd,因爲後面更新內容時,要用到它

同樣的,在 _LoginPartial.cshtml中的登錄分支裏添加:

setTimeout("RefreshMyMessageTitle()", 10000);

頁面開始加載後10秒開始更新我的消息信息。10秒鐘,是爲了儘量使整個頁面加載完畢後再開始,否則可能會因爲沒有加載完而導致錯誤提示,而且也沒有辦法更新。

後面的實現內容,主要分三部分:後臺、局部視圖的頁面、js輪訓

一、 後臺的實現

action對應局部視圖的名稱,我這裏的名稱爲:MyMessageTitle

        public ActionResult MyMessageTitle()
        {
            IsLogined();

            UserMessageModel viewModel = new UserMessageModel();
            viewModel.newMsgCount = ...;  // 獲取新消息的數量

            return PartialView("MyMessageTitle", viewModel);
        }

這裏就是獲取新的消息數量,然後附給模型

二、頁面

頁面的名稱:MyMessageTitle.cshtml
位置:在Home目錄中,這個位置很重要,因爲後面刷新時要用到

內容就很簡單:

@using fwVer.Models
@model UserMessageModel
@{
    // 只有用戶登錄的情況下,纔會加載此視圖
    string strUserInfo = "我的消息";
    if (Model.newMsgCount > 0)
    {
        strUserInfo += $"(<font color=\"red\">{Model.newMsgCount}</font>)";
    }
    @Html.Raw(strUserInfo)
}

這個的輸出,就是一個字符串,如果有新消息,個數就是紅色的

三、js輪訓

function RefreshMyMessageTitle() {
    $.ajax(
        {
            type:"GET",
            url: '/home/home/MyMessageTitle',
            success: function (data) {
                $('#myMessageTitle_ihd').html(data);
                setTimeout("RefreshMyMessageTitle()", 5000);
            },

            error: function (errMsg) {
                console.log(errMsg);
                setTimeout("RefreshMyMessageTitle()", 5000);
            }
        });
}

這個部分的代碼,我只寫了最少的部分,沒有任何多餘的東西存在。

不管是成功還是失敗,都在5鍾後再次刷新

這裏就直接刷新上面提到的ID的內容即可。

 

2019.10.19更新:

今天學習了一下Ajax,發現這個地址對本文很有幫助:

https://www.w3school.com.cn/ajax/ajax_xmlhttprequest_send.asp

這個網站確實不錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章