如何在 MVC 的视图中显示 Razor 和 C# 代码

How to display razor and C# code in view in MVC

我正在使用 MVC 和 razor 作为样式指南。我需要在视图中显示代码,以便其他人可以在网站上使用它。 我需要在 Razor 助手不执行函数的情况下显示代码。

我正在尝试通过 Razor 助手来执行此操作。我希望这个助手渲染按钮并在视图中显示确切的 MVC Razor 助手代码(而不是让它显示助手输出的 HTML)。

@helper ShowCode() { 
        <div>
            @Html.TextBox("textBox")
        </div>
    }

然后我调用下面的帮助程序并尝试显示代码:

   // render the button
   @ShowCode()

        // display the button code
        <pre>
            <code>
                @ShowCode().ToString()
            </code>
        </pre>

但是,这会显示以下内容:

我需要它来显示以下代码而不是 HTML:

 <div>
    @Html.TextBox("textBox")
 </div>

如何在 Razor 助手中显示代码而不将其输出为 html? (我想准确显示 Razor 助手中的内容)。这可能吗?

你实际上不能那样做。 Razor returns HTML 无法将实际的 Razor 模板代码作为字符串获取。