Talking about ASP.NET Core 2.0 layout page

Time:2020-11-12

This paper introduces the ASP.NET The core 2.0 layout page is shared with you as follows:

problem

How to ASP.NET Sharing visible elements, code blocks, and instructions in a core 2.0 project?

answer

Create an empty project. First add the greetingservice service and the userviewmodel model


public interface IGreetingService

{

  string Greet(string firstname, string surname);

}

 

public class GreetingService : IGreetingService

{

  public string Greet(string firstname, string surname)

  {

    return $"Hello {firstname} {surname}";

  }

} 

Then add MVC service and greetingservice service in startup, and configure MVC middleware


public void ConfigureServices(IServiceCollection services)

{

  services.AddScoped<IGreetingService, GreetingService>();

  services.AddMvc();

}

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

  if (env.IsDevelopment())

  {

    app.UseDeveloperExceptionPage();

  }

 

  app.UseMvc(routes =>

  {

    routes.MapRoute(

      name: "default",

      template: "{controller=Home}/{action=Index}/{id?}");

  });

} 

Add the controller homecontroller, modify the index method and return viewresult:


public class HomeController : Controller

{

  public IActionResult Index()

  {

    var model = new UserViewModel

    {

      Firstname = "Tahir",

      Surname = "Naushad"

    };

    return View(model);

  }

} 

Add layout page (_ Layout.cshtml ):


<!DOCTYPE html>

<html>

<head>

  <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 views and pay attention to the naming convention (Views / home)/ Index.cshtml ):


@model UserViewModel

@{

  ViewBag.Title = "ASP.NET Core";

}

<h2>I'm in View page</h2>

<p>@Greeter.Greet(@Model.Firstname, @Model.Surname)</p>

@section footer{

  <h3>I'm in footer section</h3>

}

 

@*

  @section links{

    <a href="http://www.cnblogs.com/sanshi/" rel="external nofollow" target="_blank">Blog</a>

  }

*@ 

Add import page (_ ViewImports.cshtml ):


@using LayoutPage.Models

@inject IGreetingService Greeter 

Add start page (_ ViewStart.cshtml ):


@{

  Layout = "_Layout";

} 

The completed directory structure is as follows:

Run, the page displays:

discuss

ASP.NET Core provides a way to reuse visible elements and common code between different views

1. Layout page

2. Start page

3. Import page

Layout page (_ Layout.cshtml )

Layout pages are used to share common visible elements between different pages to provide a consistent look and feel for the entire application.

The layout page is added to the views / shared directory and named_ Layout.cshtml (rules of engagement). You can place multiple layout pages in one application.

The view has a layout property that sets which layout to use. ASP.NET The core first looks for the layout in the view related folder, and if not, in the shared directory. The layout page calls the @ renderbody method to render the contents of the view.

If the_ Layout.cshtml Delete, we can see the order of finding paths from the exception information:

Layout pages can also use @ rendersection to determine which paragraph in the view to replace. These paragraphs can be required or optional. The view uses @ section to define the contents of these paragraphs. In the layout page, issectiondefined can be used to determine whether a paragraph is defined in the view, and the corresponding processing can be carried out according to the judgment results


@if (IsSectionDefined("links"))

{

  @RenderSection("links", required: false)

}

else

{

  <em>No social media links supplied</em>

} 

Import page (_ ViewImports.cshtml )

As we discussed in the previous article, views can use directives to do many things, such as importing a namespace (@ using), injecting dependencies (@ inject), and declaring model types (@ model). MVC also provides an import page to declare common instructions for one or more views.

The import page is usually added to the views directory and named_ ViewImports.cshtml 。 It can also be added to other directories (such as the view directory), in which case it will be applied to the views (including subdirectories) below this directory.

If there are multiple import pages, the instruction closest to the view (such as @ model, @ inject) is used, or all instructions are combined together (such as @ using, @ addtaghelper).

Start page (_ ViewStart.cshtml )

MVC provides a mechanism to run code before all views, which is the start page. The start page runs before each view, except for layout pages and partial views.

The start page is usually added to the views directory and named_ ViewStart.cshtml 。 If there are multiple start pages, they are executed in a hierarchical order, from root to subdirectory.

The start page is often used to set the layout page for all views in the catalog.

Download source code

Original text: https://tahirnaushad.com/2017/08/23/asp-net-core-2-0-mvc-layout-pages/

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.