Click here to Skip to main content
15,868,109 members
Articles / Web Development / ASP.NET

ASP.NET Core 2.0 MVC Layout Pages

Rate me:
Please Sign up or sign in to vote.
1.80/5 (2 votes)
28 Aug 2017CPOL2 min read 11.6K   1   2
How to share common visual elements, code blocks and directives in ASP.NET Core MVC. Continue reading...

Problem

How to share common visual elements, code blocks and directives in ASP.NET Core MVC.

Solution

In an empty project, amend Startup class to add services and middleware for MVC:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddScoped<IGreetingService, GreetingService>();
            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Add a service and model:

C#
public interface IGreetingService
    {
        string Greet(string firstname, string surname);
    }

    public class GreetingService : IGreetingService
    {
        public string Greet(string firstname, string surname)
        {
            return $"Hello {firstname} {surname}";
        }
    }

    public class UserViewModel
    {
        public string Firstname { get; set; }
        public string Surname { get; set; }
    }

Add a controller with action method returning ViewResult:

C#
public IActionResult Index()
        {
            var model = new UserViewModel
            {
                Firstname = "Tahir",
                Surname = "Naushad"
            };
            return View(model);
        }

Add _Layout.cshtml:

HTML
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        <h1>I'm in Layout page</h1>
        @RenderBody()
        @RenderSection("footer", required: false)
        @if (IsSectionDefined("links"))
        {
            @RenderSection("links", required: false)
        }
        else
        {
            <em>No social media links supplied</em>
        }
    </div>
</body>
</html>

Add Index.cshtml:

HTML
@model UserViewModel
@{ 
    ViewBag.Title = "ASP.NET Core MVC";
}
<h2>I'm in View page</h2>
<p>@Greeter.Greet(@Model.Firstname, @Model.Surname)</p>
@section footer{
    <h3>I'm in footer section</h3>
}

Add _ViewImports.cshtml:

C#
@using Fiver.Mvc.Layout.Models.Home
@inject IGreetingService Greeter

Add _ViewStart.cshtml:

C#
@{
    Layout = "_Layout";
}

Discussion

ASP.NET Core MVC provides ways to reuse and share visual elements and common code between different views. These are:

  1. Layout Page
  2. Start Page
  3. Imports Page

Layout Page

These are used to share common visual elements in your pages and provide a consistence look and feel throughout your application.

Layout page is added to the Views/Shared folder and is named (as a convention) _Layout.cshtml. There can be more than one layout pages in your application too.

Views have a Layout property through which they set the layout to use. The layout page is searched in controller specific folder and then in shared folder. Layout page calls @RenderBody method to render the contents of a view.

Layout page can also use @RenderSection to decide where sections defined in views will be placed. These sections can be required or optional. Views define the contents of a section using @section syntax. Layout page can check if a section is defined in the view and act accordingly using IsSectionDefined method on the view:

C#
@if (IsSectionDefined("links"))
        {
            @RenderSection("links", required: false)
        }
        else
        {
            <em>No social media links supplied</em>
        }

Import Page

As we discussed in Razor post, views can  use directives for a number of things, e.g., importing namespaces (@using), injecting dependencies (@inject) and declaring model type (@model). MVC provides an import page to declare directives common to one or more views.

Import page is added usually in Views folder and is named _ViewImports.cshtml. It can also be added to other folders (e.g., controller specific views folder) however, in this case it will apply to views inside this folder (and its subfolders).

In case of multiple import pages, either the directives close to the views are used (e.g. @model, @inject) or all are combined (@using, @addTagHelper).

Start Page

MVC provides a mechanism to run code common to all views using a start page. Start page run before every view, except for layout page and partial views.

Start page is added usually in Views folder and is named _ViewStart.cshtml. There can be multiple start pages, in which case they will run in hierarchical order, from root to subfolders.

Start page is often used to set the Layout page for all the views in a folder.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
PraiseGreat Pin
frankus12328-Aug-17 10:23
frankus12328-Aug-17 10:23 
GeneralRe: Great Pin
User 104326428-Aug-17 11:44
User 104326428-Aug-17 11:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.