无论用户在哪个页面,都会将数据发送到_Layout.cshtml的标头

时间:2016-12-21 14:59:49

标签: c# asp.net asp.net-mvc razor asp.net-core-mvc

我的_Layout.cshtml文件的标题中有通知徽章。这样我就可以不断向用户显示他们的通知,无论他们在哪个页面上。

<a href="#">Notifications <span class="badge">@ViewData["NotificationCount"]</span></a><br>

但是,我想知道是否有更好的方法来做到这一点。似乎我需要在每个观点的顶部执行以下操作:

@{
    ViewData["ReminderCount"] = Model.Notifications.Count();
}

这也意味着我需要在整个应用程序中将通知列表作为每个页面ViewModel的一部分。

我在这里遗漏了什么吗?我觉得在ASP.NET MVC中必须有更好的方法来处理这样的事情。

理想的做法是在用户登录后立即加载用户的通知并转到其信息中心,然后继续在所有页面上显示该号码,除非他们检查通知,然后清除号码。

1 个答案:

答案 0 :(得分:1)

您可以做的是创建一个操作并针对该操作创建一个局部视图,并在 _Layout.cshtml 中调用它,这将使您免于代码重复和select col1,col2, (select count(*)+1 from tablename t1 where t1.col1=t.col1 and t1.col2<t.col2) as nr from tablename t :< / p>

您的操作代码如下所示:

ViewData

您的部分视图 _NotificationsPartial.cshtml 就像:

public ActionResult Notifications()
{
   var model = Model.Notifications.Count();
   return View("_NotificationsPartial",model);
}

现在您只需要在 _Layout.csthml 中调用它:

@model System.Int32

<a href="#">Notifications 
<span class="badge">@Model</span>