Jesse Lynn
Jesse Lynn

Reputation: 325

Shared helper functions in Razor

In my C# project, I have a file titled MyHelpers.cshtml under the App_Code folder, containing the following code:

    @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>
    }

I created a MyTest.cshtml directly in the root folder, with the following content:

<!DOCTYPE html>
  <head>
    <title>Test Helpers Page</title>
  </head>
  <body>
    <p>This is some opening paragraph text.</p>

    <!-- Insert the call to your note helper here. -->
    @MyHelpers.MakeNote("My test note content.")

    <p>This is some following text.</p>
  </body>
</html>

App_Code/MyHelpers.cshtml works when called from MyTest.cshtml.

I am using RazorEngine to generate HTML emails, and my actual template files are stored in a folder named EmailTemplates. When I insert the same line @MyHelpers.MakeNote("My test note content.") as I did with MyTest.cshtml in any CSHTML file in EmailTemplates, I get the following error:

The server encountered an error processing the request.
The exception message is 'Unable to compile template.
The name 'MyHelpers' does not exist in the current context.
Other compilation errors may have occurred.
Check the Errors property for more information.'

How do I get the CSHTML files in the EmailTemplates folder to use the MakeNote function in App_Code/MyHelpers.cshtml , just as how MyTest.cshtml uses it?

Upvotes: 2

Views: 1444

Answers (1)

Gene R
Gene R

Reputation: 3744

I do such things another way.

@Html.Action("MakeNote", "Helper", "My test note content.")

Where Helper is a controller with action MakeNote

[ChildActionOnly]
public ActionResult MakeNote(string model)
{
    return PatialView(model);
}

and partial view is located in ~/Views/Helper/MakeNote.cshtml

Upvotes: 4

Related Questions