如何像 asp:Literal 一样使用 Razor?

如何像 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的类型code> 您的视图模型类型的成员为 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.