Move common razor helpers to another file

2019-03-19 07:42发布

问题:

I have a MVC4 web app and i currently have a few @helper's that i use on multiple pages, defined within cshtml. The problem is, i have to define them on each page they are used. Is it possible to create a .cshtml file that contains all of my @helper's and include that page into my views?

i.e. this is used on every Index view in the cms area.

@helper DisplayPager(Int32 CurrentPage, Int32 MaxPages) {
    String IsActive = "";
    <div class="pagination pagination-centered">
        <ul>
            <li><a href="@Url.Action("Index", new { id = CurrentPage - 1 > 0 ? CurrentPage - 1 : 1 })">Prev</a></li>
            @for (int i = 0; i < MaxPages; i++)
            {
                IsActive = ((i + 1) == CurrentPage) ? "active" : "";

                <li class="@(IsActive)"><a href="@Url.Action("Index", new { id = i + 1 })">@(i + 1)</a></li>       
            }
            <li><a href="@Url.Action("Index", new { id = CurrentPage + 1 < MaxPages ? CurrentPage + 1 : MaxPages })">Next</a></li>
        </ul>
    </div>
}

Same definition, same code, same everything, but it is in the code at least 15 times now.

回答1:

Here is instructions to achieve that

This procedure shows you how to create the helper that creates the note, as just described. This is a simple example, but the custom helper can include any markup and ASP.NET code that you need.

  1. In the root folder of the website, create a folder named App_Code. This is a reserved folder name in ASP.NET where you can put code for components like helpers.

  2. In the App_Code folder create a new .cshtml file and name it MyHelpers.cshtml.

  3. Replace the existing content with the following:

    @helper MakeNote(string content) 
    {
      <div class="note" 
           style="border: 1px solid black; width: 90%; padding: 5px; margin-left: 15px;">
        <p>
          <strong>Note</strong>&nbsp;&nbsp; @content
        </p>
      </div>
    }
    

    The code uses the @helper syntax to declare a new helper named MakeNote. This particular helper lets you pass a parameter named content that can contain a combination of text and markup. The helper inserts the string into the note body using the @content variable.

    Notice that the file is named MyHelpers.cshtml, but the helper is named MakeNote. You can put multiple custom helpers into a single file.

  4. Save and close the file.

Copied it from this article