Razor code reuse

Razor code reuse

  The Razor syntax was explained in the previous blog . In this blog post, I will learn with you how to reuse code in Razor.

1. Layout reuse

  The use of Layout, just like the template page of WebForm, will be even simpler, more convenient and clear.

  To use Layout, first add the @RenderBody() method in the corresponding position of the template page:

<!DOCTYPE html>

<html lang="en">
        <meta charset="utf-8"/>
        <title>Test site-@Page.Title</title>

  In the page to use the template page, specify the template page to be used:

    Layout = "/LayoutPage.cshtml";
    Page.Title = "The first subpage";

<p>This is a layout test</p>

  The loading sequence of Layout is different from the template page, it loads the subpages first, and then loads the layout page.

2. Page reuse

  In Razor, we can easily output the HTML code of another page in the page:


  The code of SubPage is as follows:

<font color="red">This is a subpage</font>


  Section is something used in the layout page (Layout Page). The content of the Section is defined in the sub-page that uses the layout page, and the layout page can be used. If the Page1.cshtml page uses the layout page Layout.cshtml, then we can define Section in Page1.cshtml:

@section header{
    <b>Header Section</b>

@section footer{
    <b>footer Section</b>

  The code of Layout.cshtml:




  Need to explain, although I did not find the corresponding document, but when I tested, I only found this kind of usage...

4. Helper reuse

  Helper is used to simplify code writing and is usually used to process output. For example, we can build a Helper for a model to process the Html output of the model; for another example, we can create a Helper for the system menu to facilitate our use.

  To define a Helper, you need to use the @helper tag, and add the name and corresponding code after the tag:

@helper MenuEx(params string[] strs){
        @foreach(string str in strs){

  This way of writing is very similar to the static method of the class. In this MenuEx, you need to pass an array of strings as a parameter.

  In addition, we usually put a type of Helper in a cshtml file, and the file name is equivalent to the class name. For example, MenuEx is placed in the file HelperEx.cshtml, and the method of use in Page1.cshtml is as follows:

    @HelperEx.MenuEx("Microsoft", "IBM", "Apple", "Google")

  This is our customized content. In addition, the system also provides us with a series of Helpers to simplify the writing of Html. These Helpers are placed in @Html, we can use them conveniently:


  OK, that's it for this section. For more learning content, stay tuned!

Reference: https://cloud.tencent.com/developer/article/1513836 Razor Code Reuse-Cloud + Community-Tencent Cloud