Move common razor helpers to another file

前端 未结 1 1779
孤城傲影
孤城傲影 2021-02-05 18:20

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

相关标签:
1条回答
  • 2021-02-05 18:49

    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

    0 讨论(0)
提交回复
热议问题