blog

Home / DeveloperSection / Blogs / Creating Master page in MVC

Creating Master page in MVC

Manish Kumar5184 22-Feb-2017

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

<!DOCTYPEhtml>
 
<html>
<head>
    <metaname="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 

<!DOCTYPEhtml>
 
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>@ViewBag.Title</title>
    <linkhref="~/Content/bootstrap.min.css"rel="stylesheet"/>
    <scriptsrc="~/Scripts/jquery-3.1.1.min.js"></script>
    <scriptsrc="~/Scripts/bootstrap.min.js"></script>
</head>
<body>
    <divclass="container">
        <sectionclass="box">
     <navclass="navbar navbar-inverse">
  <divclass="container-fluid">
    <divclass="navbar-header">
      <aclass="navbar-brand"href="#">Mindstick</a>
    </div>
    <ulclass="nav navbar-nav">
      <liclass="active"><ahref="#">Home</a></li>
      <liclass="dropdown">
        <aclass="dropdown-toggle"data-toggle="dropdown"href="#">Page 1
        <spanclass="caret"></span></a>
        <ulclass="dropdown-menu">
          <li><ahref="#">Page 1-1</a></li>
          <li><ahref="#">Page 1-2</a></li>
          <li><ahref="#">Page 1-3</a></li>
        </ul>
      </li>
      <li><ahref="#">Page 2</a></li>
      <li><ahref="#">Page 3</a></li>
    </ul>
  </div>
</nav>
    <div>
       @RenderBody();
    </div>
        <divclass="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
{
    
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
 
        publicActionResult 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


Updated 17-Mar-2018

Leave Comment

Comments

Liked By