如何在_Layout.cshtml中的导航栏中创建徽章接收值

如何在我的ControllerWarnings的应用程序信息的所有导航中捕获_Layout.cshtml中导航栏中的徽章?

在我的ControllerWarning中,我有一个函数,当被请求时返回Json中的数值。

namespace VS.Controllers { public class ControllerWarning : Controller { private VSContext db = new VSContext(); public JsonResult GetWarning(string user) { DateTime dt = DateTime.Now.Date; int contWarning = 0; var listaAvisos = db.Warnings.Where(a => a.User== user).ToList(); var l = new List(); foreach (var item in listaAvisos) { var res = item.Data - dt; item.QtdDias = res.Days; if (res.Days <= 5 && item.Enviado != true) { contWarning++; } } return Json(contWarning); } } public ActionResult Index(){...} public ActionResult Details(int? id){...} public ActionResult Details(Warning warning){...} } 

位于_Layout.cshtml中的Navbar有一个Badge,它应该从WarningController收集GetWarning(字符串用户)返回

 
  • @Html.ActionLink("Warning", "Index", "Warnings") @*HERE VALUE RECEIVED GETWARNING*@ GetWarning(string user)
  • 您可以让您的操作方法返回徽章的HTML,其中包括数据(警告编号)。

     public class WarningController : Controller { public ActionResult Badge() { int contWarning = 10; // temp hard coded value for demo; // Replace the hard coded value // with your existing code to get the data from database return PartialView("Badge",contWarning); } } 

    现在,在你的Badge.cshtml ,它被强行输入为int类型,呈现你想要的HTML。

     @model int  @Model  

    现在在你的布局( _Layout.cshtml )中,使用Html.Action方法调用此渲染这个Badge动作方法的输出。

      @Html.Action("Badge","Warning") 

    确保使用PartialView而不是View方法返回局部视图(没有自己的布局)。 如果您的Badge操作方法返回的视图具有相同的布局文件,那么将导致无限循环,您将获得StackOverflowexception。