如何像 asp:Literal 一样使用 Razor? [英] How to use Razor like asp:Literal?

查看:49
本文介绍了如何像 asp:Literal 一样使用 Razor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模型:

public class MyModel
{
     public string Text{get;set;}
}

我有一个视图,它呈现 MyModel 的 Text 属性:

I have a View, which renders Text property of MyModel:

<p>@Model.Text</p>

如何从 Text like 标签渲染 html 标签?例如,我有文本Text".我想在标签 p 内得到粗体文本作为结果:

How can I render html tags from Text like tags? For example, I have Text "<b>Text</b>". I want to get bold text inside tag p as result:

文字

但 Razor 按原样呈现文本:

But Razor renders text as is:

<b>Text</b>

推荐答案

我认为你需要像这样使用它:

I think you need to use it like:

<p>@Html.Raw(Model.Text)</p>

您可以在此处找到更多信息在 Phil Haack 的博客上.

You can find more info here on Phil Haack's blog.

anurse 在评论中指出,您也可以设置Text 您的视图模型类型的成员为 IHtmlString 并且只需使用 @Model.Text 来输出它.ASP.NET MVC 足够聪明,意识到输出不应该被转义.

anurse points out in the comments that you could, alternatively, set the type of the Text member of your View Model type as IHtmlString and just use @Model.Text to output it. ASP.NET MVC is clever enough to realize that the output should not be escaped.

这篇关于如何像 asp:Literal 一样使用 Razor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆