首页 > 解决方案 > MVC:从模型/控制器传递到视图时如何将字符串解析为 html dom 元素

问题描述

其中一个模型具有“描述”属性,该属性以字符串格式返回 html。喜欢 ”... ”。在没有 Js 代码的情况下加载页面时如何在视图中显示它。直接在这一行:

   <td style="max-width: 600px">
      <%: Html.DisplayFor(modelItem => item.description) %>
   </td>

我应该放什么而不是“ modelItem.description ”?

我试过了

<%: Html.DisplayFor(modelitem =>HttpUtility.HtmlEncode(item.description)) %>

但它返回以下错误

System.InvalidOperationException: 'Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.'

标签: asp.net-mvcdomrazor

解决方案


原因是因为 我不能在Displayfor<%: Html.DisplayFor... %>中使用编码

以下是显示它的正确方法之一:

<%: Html.Raw(HttpUtility.HtmlDecode(item.description))%>

推荐阅读