我在 MVC 3 和 Asp.net C# 中使用 Razor。
我有以下代码的视图。model.ContentBody
有一些 HTML 标签。
我需要将此 HTML 内容显示为DECODED。
我该如何更改视图中的代码?
<div class="display-field">
@Html.DisplayFor(model => model.ContentBody)
</div>
我在 MVC 3 和 Asp.net C# 中使用 Razor。
我有以下代码的视图。model.ContentBody
有一些 HTML 标签。
我需要将此 HTML 内容显示为DECODED。
我该如何更改视图中的代码?
<div class="display-field">
@Html.DisplayFor(model => model.ContentBody)
</div>
<div class="display-field">
@Html.Raw(Model.ContentBody)
</div>
这段代码解决了问题!
@Html.Raw
不适合我这里是例子: -
string name = "<p><span style="font-size: small; color: #ff0000;"><span style="font-size: small;">&nbsp;<span style="font-size: large; color: #000000;">Hi</span><br />&nbsp; <br />This is just a sample,<br />This will not work with @Html.Raw(),<br />";
<span>@Html.Raw(name);</span>
但这反而起作用了:-
@MvcHtmlString.Create(HttpUtility.HtmlDecode(@model.ContentBody))
或者您也可以使用:-
@Html.Raw(HttpUtility.HtmlDecode(@model.ContentBody));
您还可以在将模型发送到视图之前在控制器中解码 html,
WebUtility.HtmlDecode()
public ActionResult Index(int id)
{
var content = _contentRepository.GetContent(id);
var classViewModel = new ClassViewModel
{
ContentBody = WebUtility.HtmlDecode(ClassViewModel.ContentBody)
};
return View(classViewModel);
}
好吧,总结一下..在我的服务/控制器中,同时将模型返回到视图
....
Description = WebUtility.HtmlDecode(narration.Narration1)
我的cshtml,显示tinyMCE的地方..只是定期绑定(我将HtmlAttributeHelper用于其他目的。你可以忽略它)
<div>
@Html.TextAreaFor(model => model.Description, HtmlAttributeHelper.ConditionalDisable(false, new {@class = "tinymce"}))
</div>
并在显示数据的cshtml页面中..
......
<td class="col-word-wrap">@Html.Raw(HttpUtility.HtmlDecode(@item.Narration1))</td>
请用于显示 Html 与解码一起使用。
@MvcHtmlString.Create(@Model.OurVision)
将“ContentBody”作为 MvcHtmlString 传递给您的模型,而不是字符串。
这样你就可以使用:
<div class="display-field">
@model.ContentBody
</div>
在您的控制器中获取 MvcHtmlString 只需使用:
MvcHtmlString myHtmlString = MvcHtmlString.Create("htmlcodeandtext");
该字符串也可能是 URL 编码的,所以要解码你:
@Html.Raw(HttpUtility.UrlDecode(string))
在控制器中使用此代码:
string noHTML = Regex.Replace(inputHTML, @"<[^>]+>| ", "").Trim();