[英]Sending data to header of _Layout.cshtml regardless of what page the user is on
我的_Layout.cshtml文件的标题中有一个通知徽章。 这样一来,无论他们在哪个页面上,我都可以不断向用户显示其通知。
<a href="#">Notifications <span class="badge">@ViewData["NotificationCount"]</span></a><br>
但是,我想知道是否有更好的方法可以做到这一点。 似乎我需要在每个视图的顶部执行以下操作:
@{
ViewData["ReminderCount"] = Model.Notifications.Count();
}
这也意味着我需要在整个应用程序的每个页面ViewModel中都包含一个通知列表。
我在这里想念什么吗? 我觉得必须有一种更好的方法来处理ASP.NET MVC中的此类问题。
理想的做法是在用户登录并进入仪表板后立即加载一次用户通知,然后继续在所有页面上显示该数字,除非用户检查了该通知,然后该数字将清除。
您可以做的是创建一个动作,然后针对该动作创建一个局部视图,并在_Layout.cshtml中调用它,这将使您免于代码重复和ViewData
:
您的操作代码如下所示:
public ActionResult Notifications()
{
var model = Model.Notifications.Count();
return View("_NotificationsPartial",model);
}
您的局部视图_NotificationsPartial.cshtml类似于:
@model System.Int32
<a href="#">Notifications
<span class="badge">@Model</span>
现在,您只需要在_Layout.csthml中调用它即可 :
@Html.Action("Notifications","SomeController")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.