Asp.net MVC在Razor中输出Html的两种方式

Razor中所有的Html都会自动编码,这样就不需要我们手动去编码了(安全),但在需要输出Html时就是已经转义过的Html文本了,如下所示:

1
2
3
4
@{
string thisTest = "<span style='color:red;'>测试文字</span>";
}
@thisTest;

这样在页面输出的文本就是:<span style='color:red;'>测试文字</span>而不是红色的字体了,要输出红色的字体,有下面常用的两种方式:

1、使用Razor中的Html.Raw(推荐使用这种方式):

1
2
3
4
@{
string thisTest = "<span style='color:red;'>测试文字</span>";
}
@Html.Raw(thisTest);

2、使用MvcHtmlString类来实现:

1
2
3
4
5
@{
string thisTest = "<span style='color:red;'>测试文字</span>";
var thisResult = new MvcHtmlString(thisTest);
}
@thisResult 或 @(new HtmlString(thisTest))
作者

zhang

发布于

2019-05-07

更新于

2023-09-19

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×