Skip to main content

Layout in ASP.NET MVC

Layout in ASP.NET MVC Application

Layouts are used in MVC to provide a consistent look and feel on all the pages of our application. It is the same as defining the Master Pages in asp.net webforms but MVC provides some more functionalities.

Suppose you are developing an ASP.NET web application and you want to maintain a consistent look and feel across all the pages within you web application.
You then have two options, the first one is to design the head, body and footer sections on each page. In this approach you need to write more code on each page.

The second option is to use "Master Pages” as introduced in ASP.NET 2.0. Razor also supports this concept with a feature called "layouts" that allow you to define a common site template, and then inherit its look and feel across all the views (pages) on your web application.

For instance, an application user interface may contain Header, Left menu bar, right bar and footer section that remains same in every page and only the center section changes dynamically as shown below.
Header



Left Meu Bar




Main Content



Right Bar
Footer

The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.

The razor layout view has same extension as other views, .cshtml or .vbhtml. Layout views are shared with multiple views, so it must be stored in the Shared folder of our application. For example, when we created our Data Driven Web Application in the previous article, it also created _Layout.cshtml in the Shared folder as shown below.




The auto generated .cshtml file created by our application for _Layout file for consistent look of our web application is shown below

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Database first Approach</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <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("Csharpnaija Entity Framework", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Employees", "Index", "employees")</li>
                    <li>@Html.ActionLink("Departments", "Index", "departments")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - Database first Approach</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

As you can see from the above code snippet, the layout view contains html Doctype, head and body as normal html, the only difference is call to RenderBody() and RenderSection() methods. RenderBody acts like a placeholder for other views. For example, Index.cshtml in the home folder will be injected and rendered in the layout view, where the RenderBody() method is being called.

How to Use Layout View


Layout of our application can be set in multiple ways by either using _ViewStart.cshtml or setting up path of the layout page using the Layout property in the specified view or specifying layout view name in the action method.




The code snippet of _ViewStart is has shown below




ViewStart.cshtml can also be included in sub folder of View folder to set the default layout page for all the views included in that particular subfolder only.
For example, the following _ViewStart.cshtml in employees folder, sets Layout property to _NewLayout.cshtml. So this _ViewStart.cshtml will influence all the views included in the Home folder only. So now, Index, Create,Delete and Edit views will be rendered in _NewLayout.cshtml instead of default _Layout.cshml. This is as shown below


Setting Layout property in individual view (Page)

You can also override default layout page set by _ViewStart.cshtml, by setting Layout property in each individual .cshtml view. Now the following Index and the Create Views use _NewLayout.cshtml even if _ViewStart.cshtml set _Layout.cshtml. As shown below



Specify Layout Page in ActionResult Method

You can also specify which layout page to use while rendering view from action method using View() method.
The View() method can be used to render Details view using _NewLayout.cshtml as shown below

The Rendering Methods of Layout View

The MVC View renders child Views using the following methods RenderBody() and RenderSection().

RenderBody

In layout pages, RenderBody() renders the portion of a content page that is not within a named section. It returns the HTML content to render. RenderBody is required since it's what renders each view. As shown below


RenderSection

RenderSection() is a method of the WebPageBase class. The first parameter to the "RenderSection()" helper method specifies the name of the section we want to render at that location in the layout template. The second parameter is optional and allows us to define whether the section we are rendering is required or not. If a section is "required", then Razor will throw an error at runtime if that section is not implemented within a view template that is based on the layout file (that can make it easier to track down content errors). It returns the HTML content to render.


Other Methods of Layout Views

Other methods in Layout View that enable us pass information to the users of the our web application are the Url.Content() and Html.ActionLink

Html.ActionLink(): The easiest way to render an HTML link in is to use the HTML.ActionLink() helper. With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action. ActionLink() is an extension method of the HtmlHelper class. It returns an anchor element (an element) that contains the virtual path of the specified action. When you use an ActionLink() method then you need to pass three string parameter. The parameters are linkText (the inner text of the anchor element), actionName (the name of the action) and controllerName (the name of the controller).

Url.Content(): Content() method is a method of UrlHelper class. It converts a virtual (relative) path to an application absolute path. It has one parameter of string type that is a virtual path of the content. It returns an application's absolute path. If the specified content path (parameter of the method) does not start with the tilde (~) character then this method returns contentPath unchanged. Url.Content() ensures that all links work no matter if the site is in a virtual directory or in the web site root.

Finally, we will look at how to create a new Layout file in our application. We referenced the articles of SandeepSingh Shekhawat and TutorialTeahers

Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...

Role-Based Authorization in ASP.NET MVC

Role-Based Authorization Explained The most challenge aspect of any web application is implementing its security. In traditional web development with ASP.NET (from version 2.0 onwards), we have been using Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization. But with an increase in social networking and global authentication providers, we needed an upgraded membership system. ASP.NET Identity is the new membership system for building ASP.NET web applications, phone, store, or hybrid applications using social identities for authentication and authorization. So we can now use Windows Live (e.g. Hotmail), Gmail, Facebook and Twitter for authentication before the user starts using our web application. For internal application, we need to create users and roles for providing users access to creating items, products or managing other users. Necessary references are provided by MVC 5 applicatio...