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

问题描述 投票:1回答:1

如何在我的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<Aviso>();

            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(字符串用户)返回

<li>
    @Html.ActionLink("Warning", "Index", "Warnings")
         <span class="badge">

                 @*HERE VALUE RECEIVED GETWARNING*@
                 GetWarning(string user)

         </span>
</li>
c# asp.net-mvc visual-studio
1个回答
2
投票

您可以让您的操作方法返回徽章的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);
   }
}

现在在qazxsw poi中,它是强类型的qazxsw poi类型,渲染你想要的HTML。

Badge.cshtml

现在在您的布局(int)中,使用@model int <span class="badge"> @Model </span> 方法调用此渲染此Badge操作方法的输出。

_Layout.cshtml

确保使用Html.Action而不是 @Html.Action("Badge","Warning") 方法返回局部视图(没有自己的布局)。如果您的Badge操作方法返回的视图具有相同的布局文件,那将导致无限循环,您将获得StackOverflow异常。

© www.soinside.com 2019 - 2024. All rights reserved.