Creating a Master Page in ASP.NET MVC


 Hi Folks,

 

In this blog we are going to see how to create a master page in ASP.NET MVC. Master page is a common layout shown in all pages like menus in a website will be common across the pages.

To learn about routing 

Click Here

Consuming web API in .NET core MVC using HTTP Client

Click Here




Menus will be common for all pages in a web application. So whatever we want to create a master page we use layouts in MVC.

All java script and CSS files in common also declared in Master layout.

Step1: File -> New -> Project.




Step2: select Web -> ASP.NET Web Application (.NET Framework).



Step3: Select MVC Template and click OK.


Step4: After successful creation of project you will see the below screen


Step5: Run your application you will be seeing beautiful application with top menus in web application.



Step6: Open Solution Explorer -> Views folder -> Shared Folder -> _Layout.cshtml

  This is the default layout page created by visual studio. In this page they have given Menus like Home About Contact. which is shown in the before screen. we will create our own custom layout and see how to create master layout.

 


Step7: Click on Shared folder and click Add and MVC 5 Layout Page (Razor) and give name _CustomLayout.cshtml.

Step8: Open _CustomLayout.cshtml and replace the code with below.

_CustomLayout.cshtml

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <h1> Our First Web App with Custom Layout where we have Menus</h1>
    <div>
        @RenderBody()
    </div>
</body>
</html>


Step9: Open Views folder -> Home  folder -> Index.cshtml and replace the code with below.

Here in the Home Index view we are specifying the layout to be used for the view.

Index.cshtml

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_CustomLayout.cshtml";
}


<div class="row">
    <h2>This is Home -> Index Page</h2>
</div>

Step 10: Run the Web App. we successfully created a custom Layout Master page and used it in a view.




 Thanks for reading. In our next blog we will see how to create a Controller and View in ASP.NET MVC

Post a Comment

0 Comments