Partial View with Layout in MVC
We can use partial view with layout page. Here is the sample code...
Model
public class Menu
{
public string MenuText { get; set; }
public string MenuUrl { get; set; }
public string ToolTip { get; set; }
}
Controller
I have created a common controller and HeaderMenu action to use server side code.public ActionResult HeaderMenu()
{
List<Menu> menu = new List<Menu>
{
new Menu(){ MenuText = "About", MenuUrl = "/Home/About", ToolTip = "About us"},
new Menu(){ MenuText = "Contact", MenuUrl = "/Home/Contact", ToolTip= "Contact us"},
new Menu(){ MenuText = "Products", MenuUrl = "/Products", ToolTip= "Product Catalog"}
};
return PartialView(menu);
}
View
To use "HeaderMenu" partial view in Shared folder in Views. Change the Html code as per your design.<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
@if (Model != null)
{
foreach (var item in Model)
{
<li><a href="@item.MenuUrl" title="@item.ToolTip">@item.MenuText</a></li>
}
}
</ul>
</div>
</div>
</div>
Layout page
Finally I called partial view in layout page as below<body>
@Html.Action("HeaderMenu", "Common")
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
</body>