Creating Master page in MVC

Master page or Layout is a common layout for all the pages in the web application. Suppose we want common look and feel for many pages like header, footer, logo for this we make layout in the shared folder and shared folder should be in the View folder.

Step for adding layout in the application

Create new project

Add a new folder in the view

Right click in the shared folder go to add then click new item

Creating Master page in MVC

Select MVC Layout Page

Creating Master page in MVC

When we click this will come default

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>
 


@RenderBody() is used only once in in the layout and @RenderSection is can be used multiple time

 For common look I have used some code in layout 

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-3.1.1.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <section class="box">
     <nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">Mindstick</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li class="dropdown">
        <a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1
        <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li><a href="#">Page 1-1</a></li>
          <li><a href="#">Page 1-2</a></li>
          <li><a href="#">Page 1-3</a></li>
        </ul>
      </li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
    <div>
       @RenderBody();
    </div>
        <div class="panel-footer"> Footer</div>
            </section>
      </div>
 
</body>
</html>
 


Using layout in the view

 Add controller and add action in the view 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MvcApplication6.Controllers
{
    
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            return View();
         
        }
 
 
    }
}
 

Then add index view and call master page or layout like this

@{
    Layout ="~/Views/shared/_LayoutPage.cshtml";
}
 
<h1>Hello</h1>
 


Output


Creating Master page in MVC


You can also visit this useful post

Master Page in C# Window forms

Last updated:3/17/2018 4:40:01 AM

0 Comments

Leave Comment