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

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...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...