0

i want to using PartialView in My _Layout Page and this is my PartialView code:

  @model List<WebApplication4.Models.MainMenuTable>

@foreach (var item in Model)
{
    <li class="nav-item">
        <a class="nav-link text-dark" asp-page="@item.Link">@item.Title</a>
    </li>
}

and this is my _Layout Page code:

@{
    var partialModel = new List<MainMenuTable>()
    {
   
    };
}

and:

<partial name="_MainMenu" model="partialModel"/>

but i saw nothing in result why?

Jesica
  • 9
  • 8
  • Because your `partialModel` is an empty list, so when you pass the empty list to the Partial View, and there is no item will be iterated for the `foreach` loop, thus the `foreach` loop will be skipped and nothing is rendered. Have you tried to provide at least 1 item in the `partialModel` list and see it works? – Yong Shun Aug 14 '22 at 08:57
  • Can you give me one example for partialModel? – Jesica Aug 14 '22 at 09:24
  • i Just Need to item.Link and item.Title – Jesica Aug 14 '22 at 09:24

1 Answers1

0

Your code is OK, But you need to pass some data into Partial View when you use it in _Layout.cshtml, Refer to this simple demo:

@{
        var partialModel = new List<MainMenuTable>()
        {
            new MainMenuTable
            {
                Title = "HomePage",
                Link = "index"
            },
            new MainMenuTable
            {
                Title = "PrivacyPage",
                Link = "Privacy"
            }
        };
    }

    <partial name="_MainMenu" model="partialModel"/>

enter image description here

When you don't pass any data into Partival View, It will not show in your _Layout.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12