[英]How to display encoded HTML as decoded in MVC 3 Razor?
I'm using Razor in MVC 3 and Asp.net C#.我在 MVC 3 和 Asp.net C# 中使用 Razor。
I have a View with the following code.我有一个带有以下代码的视图。
model.ContentBody
has some HTML tags. model.ContentBody
有一些 HTML 标签。
I would need display this HTML content as DECODED .我需要将此 HTML 内容显示为DECODED 。
How shall I change my code in the View?我应该如何更改视图中的代码?
<div class="display-field">
@Html.DisplayFor(model => model.ContentBody)
</div>
<div class="display-field">
@Html.Raw(Model.ContentBody)
</div>
This code solved the problem!这段代码解决了问题!
@Html.Raw
was not work for me here is example:- @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>
But this worked instead:-但这反而奏效了:-
@MvcHtmlString.Create(HttpUtility.HtmlDecode(@model.ContentBody))
or you can also use :-或者你也可以使用:-
@Html.Raw(HttpUtility.HtmlDecode(@model.ContentBody));
You could also decode html in the controller before sending the model to the view,您还可以在将模型发送到视图之前在控制器中解码 html,
WebUtility.HtmlDecode()
WebUtility.HtmlDecode()
public ActionResult Index(int id)
{
var content = _contentRepository.GetContent(id);
var classViewModel = new ClassViewModel
{
ContentBody = WebUtility.HtmlDecode(ClassViewModel.ContentBody)
};
return View(classViewModel);
}
Well, to summarize.. In my service/Controller, while returning the model to the view好吧,总结一下..在我的服务/控制器中,同时将模型返回到视图
....
Description = WebUtility.HtmlDecode(narration.Narration1)
My cshtml, where the tinyMCE is displayed.. just bind regularly (I was using HtmlAttributeHelper for other purpose. You can ignore it)我的 cshtml,显示 tinyMCE 的地方.. 只是定期绑定(我使用 HtmlAttributeHelper 用于其他目的。你可以忽略它)
<div>
@Html.TextAreaFor(model => model.Description, HtmlAttributeHelper.ConditionalDisable(false, new {@class = "tinymce"}))
</div>
And in the cshtml page where the data is displayed..并在显示数据的 cshtml 页面中..
......
<td class="col-word-wrap">@Html.Raw(HttpUtility.HtmlDecode(@item.Narration1))</td>
请用于显示带有解码的 Html 使用。
@MvcHtmlString.Create(@Model.OurVision)
Pass in "ContentBody" as MvcHtmlString to your model instead of a string.将“ContentBody”作为 MvcHtmlString 传递给您的模型而不是字符串。
This way you can just use:这样你就可以使用:
<div class="display-field">
@model.ContentBody
</div>
in your controller to get a MvcHtmlString just use:在您的控制器中获取 MvcHtmlString 只需使用:
MvcHtmlString myHtmlString = MvcHtmlString.Create("htmlcodeandtext");
该字符串也可能是 URL 编码的,因此要解码,您可以:
@Html.Raw(HttpUtility.UrlDecode(string))
在控制器中使用此代码:
string noHTML = Regex.Replace(inputHTML, @"<[^>]+>| ", "").Trim();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.