在MVC Razor视图中显示模型中的HTML字符串

时间:2014-08-21 15:49:19

标签: asp.net-mvc razor asp.net-mvc-5 html-helper

我有一个模型字段,它返回带有换行符BR标记的HTML字符串,但如何在浏览器上显示该HTML?问题在于改为换行,标签本身显示在UI上

我试图把模型放在Html.Raw(modelItem => item.Speaking)中,但是它永远不会像预期里面的字符串一样工作,并且不能将lambda表达式转换为类型'string',因为它不是委托型

以下是我尝试过的代码和评论。

<div>
  @{          
     string strTest = "<br/>Line 1 <br/> Line 2<br>";
     @Html.Raw(strTest); //This works and display as expected
     @MvcHtmlString.Create(strTest); //This works and display as expected       

     @Html.Raw(Html.DisplayFor(modelItem => item.Speaking)); //This doesn't work, its show the <br />  on the screen     
     @MvcHtmlString.Create(Html.DisplayFor(modelItem => item.Speaking).ToString());   //This doent work, its show the <br />  on the screen  
     @Html.Raw(modelItem => item.Speaking) //This throw error Cannot convert lambda expression to type string                                     
    }

 </div>

感谢任何帮助或建议。提前谢谢!

4 个答案:

答案 0 :(得分:13)

试试这个:

@(new HtmlString(stringWithMarkup))

你也可以创建一个HTML帮助器!:

@helper RawText(string s) {
    @(new HtmlString(s))
}

答案 1 :(得分:5)

MVC4

而不是使用Themes

你可以使用 @Html.Raw(modelItem => item.Speaking)

它适用于我,我希望这也能帮助别人

答案 2 :(得分:0)

您可以仅省略 DisplayFor modelItem => ,因此:

('d', 'b/d')
('e', 'b/e')
('g', 'b/d/g')
('h', 'b/d/h')
('h', 'b/e/h')
('i', 'b/e/i')
('i', 'b/d/g/i')

答案 3 :(得分:0)

MVC 5

@Html.Raw(WebUtility.HtmlDecode(item.Speaking))