Razor

时间:2015-11-19 08:17:41

标签: c# asp.net-mvc razor

在我的C#项目中,我在App_Code文件夹下有一个名为MyHelpers.cshtml的文件,其中包含以下代码:

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

我直接在根文件夹中创建了一个MyTest.cshtml,其中包含以下内容:

<!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>

从MyTest.cshtml调用时,App_Code / MyHelpers.cshtml可以正常工作。

我使用RazorEngine生成HTML电子邮件,我的实际模板文件存储在名为EmailTemplates的文件夹中。当我在EmailTemplates中的任何CSHTML文件中插入相同的行 @ MyHelpers.MakeNote(&#34;我的测试笔记内容。&#34;)时,我使用MyTest.cshtml,我得到以下内容错误:

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.'

如何在EmailTemplates文件夹中获取CSHTML文件以使用App_Code / MyHelpers.cshtml中的MakeNote函数,就像MyTest.cshtml如何使用它一样?

1 个答案:

答案 0 :(得分:3)

我以另一种方式做这些事情。

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

Helper是具有动作MakeNote的控制器

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

和部分视图位于〜/ Views / Helper / MakeNote.cshtml