Layout View and Viewstart in Asp.Net MVC

                                           Layout View and Viewstart in Asp.Net MVC

Layout View in MVC tutorials

Layout View in MVC is the same as a master page in webforms. which means, it is the common UI throughout the application. and no need to write the code for every page. just we can use this layout view where ever we want to use as a common UI on that page.

by default, MVC creates _Layour.cshtml file inside the shared folder in Views.
it has  main rendering methods in view is RenderBody() and RenderSection().

 <!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - All Tech Geeks</title>

    <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>
                @Html.ActionLink("Application name""Index""Home"new { area = "" }, new { @class = "navbar-brand" })
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
    <div class="container body-content">
        <hr />
            <p>&copy; @DateTime.Now.Year - All Tech Geeks</p>

    @RenderSection("scripts", required: false)

In the above .cshtml file, we can find the system-defined methods and HTML helper methods.
The system-defined methods are
    1.   @RenderBody() 
    2.  @RenderSection("scripts", required: false)
    3. @Scripts.Render("~/bundles/jquery")  

The Asp.Net MVC HTML Helper methods:

    1.   @Html.Partial("_LoginPartial")   
    2.   @Html.ActionLink("Home""Index""Home")

Asp.Net MVC RenderBody() :

  1.  it renders the associated view at the response in the browser. 
  2. it must present on the Layout page.
  3. multiple RenderBody() methods not allowed in the single layout page

Asp.Net MVC RenderSection() 

  1. it is not mandatory on the layout page.
  2. RenderSection method renders the part of the child view 
  3. RenderSection method runs code blocks you define in your content pages.
  4. multiple RenderSection() methods allowed in a single layout page.
  5. RenderSection method expects one parameter and it is the name of the section. If we don’t give that, an exception will be thrown. 

The important area is _Viewstart.cshtml. after designing the out layout page immediately we need to add the code inside Viewstart.cshtml. as shown below snippet.

    Layout = "~/Views/Shared/_Layout.cshtml"

No comments: