39

我在 MVC 3 和 Asp.net C# 中使用 Razor。

我有以下代码的视图。model.ContentBody有一些 HTML 标签。

我需要将此 HTML 内容显示为DECODED

我该如何更改视图中的代码?

 <div class="display-field">
        @Html.DisplayFor(model => model.ContentBody)
 </div>
4

8 回答 8

86
<div class="display-field">
    @Html.Raw(Model.ContentBody)
</div>

这段代码解决了问题!

于 2012-10-05T06:50:36.877 回答
48

@Html.Raw不适合我这里是例子: -

  string name = "&lt;p&gt;&lt;span style=&quot;font-size: small; color: #ff0000;&quot;&gt;&lt;span style=&quot;font-size: small;&quot;&gt;&amp;nbsp;&lt;span style=&quot;font-size: large; color: #000000;&quot;&gt;Hi&lt;/span&gt;&lt;br /&gt;&amp;nbsp; &lt;br /&gt;This is just a sample,&lt;br /&gt;This will not work with @Html.Raw(),&lt;br /&gt;";
  <span>@Html.Raw(name);</span>

但这反而起作用了:-

@MvcHtmlString.Create(HttpUtility.HtmlDecode(@model.ContentBody))

或者您也可以使用:-

@Html.Raw(HttpUtility.HtmlDecode(@model.ContentBody));
于 2012-10-05T06:53:38.617 回答
8

您还可以在将模型发送到视图之前在控制器中解码 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);
    }
于 2013-09-26T06:10:46.280 回答
3

好吧,总结一下..在我的服务/控制器中,同时将模型返回到视图

    ....
    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>
于 2019-02-20T16:34:42.937 回答
2

请用于显示 Html 与解码一起使用。

@MvcHtmlString.Create(@Model.OurVision)   
于 2014-02-07T08:10:57.870 回答
0

将“ContentBody”作为 MvcHtmlString 传递给您的模型,而不是字符串。

这样你就可以使用:

<div class="display-field">
        @model.ContentBody
 </div>

在您的控制器中获取 MvcHtmlString 只需使用:

MvcHtmlString myHtmlString = MvcHtmlString.Create("htmlcodeandtext");
于 2012-10-05T09:23:01.640 回答
0

该字符串也可能是 URL 编码的,所以要解码你:

@Html.Raw(HttpUtility.UrlDecode(string))
于 2021-04-06T23:30:31.807 回答
-7

在控制器中使用此代码:

string noHTML = Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim();
于 2014-07-31T06:30:38.443 回答