Html.Raw() 的 Razor 替代方案
我在一个方法中打印出 html 。这是代码:
@Html.Raw(Html.GenerateTabs()) //works -- but is inconvinent
真的不想对每个方法都这样做。这就是我想要的方式。但这不起作用。当我运行代码 html 时,会在浏览器中打印。
@Html.GenerateTabs() //prints html in the broswer
<text>@Html.GenerateTabs()</text> //prints html in the broswer
有没有一种剃须刀友好的方法来做到这一点?
I have html being printed out in a method. Here is the code:
@Html.Raw(Html.GenerateTabs()) //works -- but is inconvinent
Is really did not want to do every method like this. Here is the way i wanted to do it. But it does not work. When when I run the code html prints in the browser.
@Html.GenerateTabs() //prints html in the broswer
<text>@Html.GenerateTabs()</text> //prints html in the broswer
Is there a razor friendly way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的代码输出 MvcHtmlString 而不是字符串,它将正确输出其中包含的 HTML。
您可以使用 HTML 字符串使用其具有的静态工厂方法构造 MvcHtmlString。
然后在视图中:
If your code outputs an MvcHtmlString instead of string, it will output properly with the HTML contained therein.
You construct the MvcHtmlString with a static factory method it has, from the string with HTML.
then in view:
Razor 默认编码。到目前为止,我还没有发现在视图级别或应用程序级别将其关闭。
也许可以延期?
...
Razor encodes by default. So far I have not found at view level or application level of turning it off.
Maybe make an extension?
...
只需让您的GenerateTabs 返回一个MvcHtmlString。
它与这里的其他帖子类似,但为什么要通过另一种方法来输出原始 html 而不是仅仅指定 Html.Raw。 IE 我并不提倡像下面那样使用另一种方法,而只是确保您的GenerateTabs 返回MvcHtmlString。
Simply make your GenerateTabs return an MvcHtmlString.
Its similar to the other post here, but why go through another method to output raw html rather than just specify Html.Raw. IE I'm not advocating another method as was done below, but simply ensure your GenerateTabs returns the MvcHtmlString.
您可能想在 App_Code 文件夹中创建一个助手。
那里的代码已编译并可用于所有 Razor 视图。
添加一个文件,例如 SiteHelper.cshtml 并在其中添加一个辅助方法
然后在任何 razor 视图中使用它
You might want to create a helper in the App_Code folder.
The code there is compiled and is available to all your razor views.
Add a file say SiteHelper.cshtml and in there add a helper method
Then use it in any razor view as