【问题标题】:Displaying HTML String from Model in MVC Razor View在 MVC Razor 视图中显示模型中的 HTML 字符串
【发布时间】:2014-10-15 08:11:53
【问题描述】:

我有一个模型文件,它返回一个带有换行符 BR 标记的 HTML 字符串,但是如何在浏览器上显示该 HTML?问题在于换行符,标签本身显示在 UI 上

我试图将模型放在 Html.Raw(modelItem => item.Speaking) 中,但它永远不会工作,因为它期望里面有一个字符串,并且无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型

下面是我尝试过的代码和cmets。

<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>

感谢任何帮助或建议。提前致谢!

【问题讨论】:

  • 我的答案改了,看看吧。

标签: asp.net-mvc razor asp.net-mvc-5 html-helper


【解决方案1】:

试试这个:

@(new HtmlString(stringWithMarkup))

你也可以创建一个 HTML 助手!:

@helper RawText(string s) {
    @(new HtmlString(s))
}

【讨论】:

  • 感谢 Qualid 的回复,但这没有用。我想知道将模型值作为输入传递给 HtmlString 的方式。 @(new HtmlString(Html.DisplayFor(modelItem => item.Speaking).ToString())) 这给了我带有标记的字符串。
  • 我只需要使用 :) 感谢查看查询的人! @Html.Raw(item.Speaking) 我得到了答案,forums.asp.net/p/2004322/…
  • 它适用于 MVC 5,以防您只是在视图中显示 HTML 内容。
【解决方案2】:

MVC4

而不是使用@Html.Raw(modelItem =&gt; item.Speaking)

你可以使用 @Html.Raw(@Model.Speaking.ToString())

它对我有用,我希望这对其他人也有帮助

【讨论】:

  • 这是一篇旧帖子,但以上内容对我不起作用,但确实如此:@HTML.Raw(item.Speaking.ToString()
【解决方案3】:

您可以同时省略 DisplayFormodelItem =>,因此:

@Html.Raw(item.Speaking)

【讨论】:

    【解决方案4】:

    MVC 5

    @Html.Raw(WebUtility.HtmlDecode(item.Speaking))
    

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多