asp.net-mvc 在 MVC Razor 视图中显示模型中的 HTML 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25430648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying HTML String from Model in MVC Razor View
提问by Srééj?th Ná?r
I have a Model filed that returns an HTML string with line break BR tag, but How do I display that HTML on the browser ? The problem ins instead putting the line break, the Tag itself displaying on the UI
我有一个模型文件,它返回一个带有换行符 BR 标记的 HTML 字符串,但是如何在浏览器上显示该 HTML?问题在于换行符,标签本身显示在 UI 上
I tried to put the model within Html.Raw(modelItem => item.Speaking), but it never works as it expecting a string inside, and Cannot convert lambda expression to type 'string' because it is not a delegate type
我试图将模型放在 Html.Raw(modelItem => item.Speaking) 中,但它永远不会工作,因为它需要一个字符串,并且无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
Below is the code and comments what I've tried.
以下是我尝试过的代码和评论。
<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>
Appreciate any help or suggestions. thanks in advance!
感谢任何帮助或建议。提前致谢!
回答by Oualid KTATA
Try this :
尝试这个 :
@(new HtmlString(stringWithMarkup))
and you can create a HTML helper too!:
你也可以创建一个 HTML 助手!:
@helper RawText(string s) {
@(new HtmlString(s))
}
回答by Dashrath
In MVC4
在MVC4中
Instead of using @Html.Raw(modelItem => item.Speaking)
而不是使用 @Html.Raw(modelItem => item.Speaking)
You can use
@Html.Raw(@Model.Speaking.ToString())
您可以使用
@Html.Raw(@Model.Speaking.ToString())
It works for me and I hope this help someone else too
它对我有用,我希望这也能帮助其他人
回答by MGOwen
You can just omit both DisplayForand modelItem =>, so:
您可以省略DisplayFor和modelItem =>,因此:
@Html.Raw(item.Speaking)

