Use Layouts In ASP.NET MVC

The basic layout structure in MVC looks like this.

  1. _MyLayout.cshtml
    1. <!DOCTYPE html>  
    2. <html>  
    3.   
    4. <head>  
    5.     <meta charset="utf-8" />  
    6.     <meta name="viewport" content="width=device-width" />  
    7.     <title>@ViewBag.Title</title>  
    8.     @RenderSection("CSS", required: false)  
    9. </head>  
    10.   
    11. <body>  
    12.     @RenderBody() @RenderSection("Scripts", required: false) @RenderPage("~/Views/Shared/_Demo.cshtml")  
    13. </body>  
    14.   
    15. </html>  
    In ASP.NET MVC, at application level we have _ViewStart file within the Views folder for defining the default layout page.

  2. BundleConfig.cs
    1. public class BundleConfig  
    2. {  
    3.     public static void RegisterBundles(BundleCollection bundles)  
    4.     {  
    5.         bundles.Add(newScriptBundle("~/bundles/bootstrap")  
    6.             .Include(  
    7.                 "~/Scripts/bootstrap.js""~/Scripts/respond.js"));  
    8.         bundles.Add(newStyleBundle("~/Content/css")  
    9.             .Include("~/Content/bootstrap.css""~/Content/site.css"));  
    10.     }  
    11. }  
    1. Scripts.Render generates script tags for each item in Script bundle when optimizations are disabled.

    2. Styles.Render generates multiple style tags in the CSS bundle.

  3. Index.cshtml
    1. @{  
    2.     ViewBag.Title = "Home";  
    3.     Layout = "~/Views/_MyLayout.cshtml";  
    4. }  
    5. <!-- MAIN-->  
    6. <div id="main">  
    7.    <!-- @RenderBody()renders here.-->  
    8.    Hi , This is Demo.  
    9. </div>  
    10. //This section render in header part according to our _LayoutPage.cshtml.  
    11. @section CSS {  
    12.   
    13.    @Styles.Render("~/Content/css")  
    14.    <link href="~/Content/css/jquery-ui.css"rel="stylesheet"/>  
    15.    <link href="~/Content/js/rating/jquery.rateyo.css"rel="stylesheet"/>  
    16. }  
    17.   
    18. //This section render in body part according to our _LayoutPage.cshtml.  
    19. @section Scripts {  
    20.   
    21.    @Scripts.Render("~/bundles/bootstrap ")  
    22.    <script src="~/Content/js/jquery-ui.min.js"></script>  
    23.    <script src="~/Content/js/rating/jquery.rateyo.js"></script>  
    24.   
    25. }  
  4. @RenderPage()

    RenderPage method exists in our Layout Page to render the other page if you want.

    Example
    1. @RenderPage("~/Views/Shared/_Demo.cshtml")  
Ebook Download
View all
Learn
View all