如何在C#字符串属性中插入HTML标记?

REM*_*ESQ 2 c# asp.net-mvc-3

不确定如果可能,但我在课堂上有这个:

public string TextNotIncluded 
{ 
    get
    { 
        return ("which is <u>not</u> included in the Quote");
    }
}
Run Code Online (Sandbox Code Playgroud)

<u></u>被显示在我看来,而非字不被强调.我不熟悉C#.

任何人都可以提供快速解答吗?

谢谢.

编辑:

我只是在我的观点中这样说:@MyClass.TextNotIncluded.@Html.Raw在我的情况下,将它包装起来并不高效,因为我在整个数十个视图中都散布了它.

p.s*_*w.g 9

这样做没有任何根本性的错误,但它可能无法呈现您期望的方式.

您可以@Html.Raw像其他人建议的那样使用,但我认为最好以表明它可能包含html的方式显式声明您的模型.您可能希望使用MvcHtmlString该类来代替:

public MvcHtmlString TextNotIncluded 
{ 
    get { return MvcHtmlString.Create("which is <u>not</u> included in the Quote"); }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的视图中,您可以使用:

@Model.TextNotIncluded
Run Code Online (Sandbox Code Playgroud)

  • @JoeEnos是的,但是FWIW,您可能希望将视图模型与数据模型分开. (3认同)

Joe*_*nos 7

如果您使用的是Razor,默认情况下字符串是HTML编码的 - 您需要使用它Html.Raw来关闭编码:

@Html.Raw(x.TextNotIncluded)
Run Code Online (Sandbox Code Playgroud)

在ASPX引擎中,您将使用 <%= %>

<%= x.TextNotIncluded %> - this gives you the raw text
<%: x.TextNotIncluded %> - this HTML-encodes your text - you don't want this.
Run Code Online (Sandbox Code Playgroud)