在C#Razor中将字符串呈现为HTML

时间:2022-11-07 04:05:21

I am attempting to render an address from my model. The string contains line breaks that I am replacing with a break tag. Although, it is rendering on the page as a string instead as HTML. How can I force my string to render as HTML instead?

我试图从我的模型中渲染一个地址。该字符串包含我用break标记替换的换行符。虽然,它在页面上呈现为字符串而不是HTML。如何强制我的字符串呈现为HTML?

Attempt:

尝试:

<span id="addressLine">
    @Model.MyData.Address.Replace("\r\n", "<br />");
</span>

Result on page:

页面结果:

Address Top<br />Street Name<br />City<br />PostCode

Should be displayed as:

应显示为:

Address Top
Street Name
City
PostCode

4 个解决方案

#1


12  

Use @Html.Raw(Model.MyData.Address.Replace("\r\n", "<br />"))

使用@ Html.Raw(Model.MyData.Address.Replace(“\ r \ n”,“
”))

#2


3  

Use

使用

@(new HtmlString(@Model.MyData.Address))

See this post: Rendering HTML as HTML in Razor

请参阅此文章:在Razor中将HTML呈现为HTML

#3


1  

You should use CSS whitespace property instead of it. For more details, access http://www.w3schools.com/cssref/pr_text_white-space.asp

您应该使用CSS空白属性而不是它。有关更多详细信息,请访问http://www.w3schools.com/cssref/pr_text_white-space.asp

It also helps you avoiding Cross-site scripting (http://en.wikipedia.org/wiki/Cross-site_scripting)

它还可以帮助您避免跨站点脚本(http://en.wikipedia.org/wiki/Cross-site_scripting)

#4


0  

Use css to preserve the white space

使用css保留空白区域

Html

HTML

<div id="addressLine">
  @Model.MyData.Address;
</div>

Css

CSS

#addressLine {
  white-space: pre;
}

#1


12  

Use @Html.Raw(Model.MyData.Address.Replace("\r\n", "<br />"))

使用@ Html.Raw(Model.MyData.Address.Replace(“\ r \ n”,“
”))

#2


3  

Use

使用

@(new HtmlString(@Model.MyData.Address))

See this post: Rendering HTML as HTML in Razor

请参阅此文章:在Razor中将HTML呈现为HTML

#3


1  

You should use CSS whitespace property instead of it. For more details, access http://www.w3schools.com/cssref/pr_text_white-space.asp

您应该使用CSS空白属性而不是它。有关更多详细信息,请访问http://www.w3schools.com/cssref/pr_text_white-space.asp

It also helps you avoiding Cross-site scripting (http://en.wikipedia.org/wiki/Cross-site_scripting)

它还可以帮助您避免跨站点脚本(http://en.wikipedia.org/wiki/Cross-site_scripting)

#4


0  

Use css to preserve the white space

使用css保留空白区域

Html

HTML

<div id="addressLine">
  @Model.MyData.Address;
</div>

Css

CSS

#addressLine {
  white-space: pre;
}