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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...