Mark Tabor

Mark Tabor

  • 589
  • 2k
  • 460k

How to call A partial view from _Layout.cshtml {partial view

May 12 2016 3:24 PM

I have downloaded an application In where I have _Layout.cshtml and in this _Layout.cshtml I am calling a Partial View _Hearder the Partial view code is as below

<div id="siteHeader">

<div class="row">

<div class="four columns">

<p class="site-title">

<a href="@Url.Action("Index", "Home")">

<img src="~/Images/rrr.png" alt="" />

</a>

</p>

</div>

<div class="eight columns">

<ul class="nav-bar">

<li><a href="#showcase" class="main">Home</a></li>

<li>@Html.ActionLink("Services","Index","Services")</li>

<li>@Html.ActionLink("News","Index","News")</li>

<li><a href="#media" class="main">For Sale</a></li>

<li><a href="#media" class="main">For Rent</a></li>

<li><a href="#media" class="main">Contact Us</a></li>

</ul>

</div>

</div>

</div>

Now I want to made this _Header to get data from data base table what should i do ? i am newby MVC developer

What I have Done :

I have done a demo project in which i have created a Menu controller and i have already add entity data model which was basically my menu table then my controller is having that code

Menu Controller :

private TestEntities testEntities = new TestEntities();

public ActionResult Index()

{

ViewBag.MenuLevel1 = this.testEntities.Menus.Where(menu=>menu.ParentId==null ).ToList();

return View();

}

and I have a Folder Inside Views Folder I have Menu Folder and in Menu folder i have Index view having below code

@Model Menu.ModelTest

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width" />

<title>Index</title>

</head>

<body>

<div>

<ul>

@foreach (var menuLevel1 in ViewBag.MenuLevel1)

{

<li>@menuLevel1.Name

@if (menuLevel1.Child.Count > 0)

{

<ul>

@foreach (var menuLevel2 in menuLevel1.Child)

{

<li>

@menuLevel2.Name

</li>

}

</ul>

}

</li>

}

</ul>

</div>

</body>

</html>

This runs fine i want to made this as partial view and then I want to call this partial view from _Layout , I have know how about simple Partial view but this Partial View is having Controller Action method as well so how to call This Partial view from _Layout.cshtml whatever my _Layout.cshtml is not using any Model.


Answers (8)