Home > Blockchain >  Using Asp.Net Core Viewbag
Using Asp.Net Core Viewbag

Time:05-15

Layout.cshtml

  @{ 
        var menus = (IEnumerable<WebApplication.Models.TopMenu>)ViewBag.menus;
    
    }


  <div >
         <!-- Menu Partial -->
    @await Html.PartialAsync("~/Views/MainPage/TopMenu.cshtml", menus);
  </div>

MainPageController.cs

  public IActionResult Mainpage()
        {

 
            ViewBag.menus = db.TopMenu.Where(a => a.Active).OrderBy(a => a.Order);



            return View();
        }

TopMenu.cshtml

@{ 
    Layout = null;
}


@model IEnumerable<WebApplication.Models.TopMenu>
<ul id="nav"  >
    <li><a href="#">MainPage</a></li>
    @{ 
        foreach (var item in Model)
        {
                <li>
                    @if (item.ParentId == null && Model.Where(a => a.ParentId == item.Id).Any())
                    {
                    <a href="/PageDetail/@[email protected]">@item.Name</a>
                    }
                    else if (item.ParentId == null && Model.Where(a => a.ParentId != item.Id).Any())
                    {
                        var link = "";
                        if (!String.IsNullOrEmpty(item.Link)) { link = item.Link; }
                        else { link = "/PageDetail"   item.Name   "-"   item.Id; }
                        <a href="@link">@item.Name</a>

                    }
                <ul>
    @foreach (var item1 in Model.Where(a => a.ParentId == item.Id))
    {
        <li><a style="text-transform:none;" href="/PageDetail/@[email protected]" ></a></li>


    }
                 </ul>
               
        </li> 
            }

        }
</ul>
      

I'm trying to show the top menu names from using database . Doesn't work and doesn't give an error.I tried to migrate with view bag and I am using ms sql. What should i do to get the menu names?

CodePudding user response:

1_create _ViewImports.cshtml in Views folder write this line

@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers 

2_use tagHelper in Layout.cshtml

@{
      var menus = (IEnumerable<WebApplication.Models.TopMenu>)ViewBag.menus; 
    }

  <div >
         <!-- Menu Partial -->
         <partial name="TopMenu.cshtml" model="@menus" />  
  </div>

other

<partial name="~/Views/MainPage/TopMenu.cshtml" model="@menus" />

CodePudding user response:

It might be because you forgot to add data in a html tag.

<a style="text-transform:none;" href="/PageDetail/@[email protected]" >@item.Title</a>
  • Related