【问题标题】:Convert @Html.Raw to string in ASP.NET MVC 4 Razor在 ASP.NET MVC 4 Razor 中将 @Html.Raw 转换为字符串
【发布时间】:2014-10-26 03:37:00
【问题描述】:

我想要的是将输出的 IHtmlString 转换为字符串。

我有这个代码:

string text = @Html.Raw(Model.lastNoticias.Descricao);

此代码返回错误:

无法将 System.Web.IHtmlString 类型隐式转换为字符串。

完整代码:

@{ 
    string text = @Html.Raw(Model.lastNoticias.Descricao);
}
@if (text.Length > 100)
{
    @(text.Substring(0, 100) + "... ");
}

我该怎么做?

【问题讨论】:

  • string text = Model.lastNoticias.Descricao; ?
  • Model.lastNoticias.Descricao 是一个编码的 html。我需要解码它并在获取子字符串之后。

标签: c# html asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

成功了:

@{ string text = "any text"; } @Regex.Replace(text, @"<[^>]*>", "").Substring(0, 80);

【讨论】:

  • 欢迎来到 StackOverflow!您正在回答的问题已经有一个公认的答案。您的回答与社区准则不符,可能应该是评论。
【解决方案2】:
@if (Model.lastNoticias.Descricao.Length > 100)
{
    @Html.Raw(Model.lastNoticias.Descricao.Substring(0, 100) + " ...");
}
else
{
    @Html.Raw(Model.lastNoticias.Descricao);
}

另请注意,您不想修剪转义字符串。你永远不知道你在修剪什么。这里的解决方案是正确的。

【讨论】:

  • 比你需要删除html标签。或者修剪时需要补全未闭合的html标签。以下是完成未封闭标签所需的代码:gist.github.com/kad1r/b92454f76e5b8c017b2e
  • 但问题是 Model.LasNoticias.Descricao.Length 是一个编码的 html。如果我做出上面的解决方案,它也会计算 html 标签。例如:`@{ string h = "teste"; } @("h 值是:" + h.Substring(0,5)) ` 结果是: `
  • 基本上,我想要的是获取解码后的文本,然后测试它是否> 100,然后获取子字符串。我该怎么做?
  • 我告诉过你,你有两种选择。首先,您需要从字符串 (stackoverflow.com/questions/4878452/remove-html-tags-in-string) 中删除所有 html 标签,第二个是修剪并完成未封闭的 html 标签。我给你的代码就是这样做的,即使你像“asdaj
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 2018-03-27
  • 2021-05-13
  • 1970-01-01
  • 2014-02-11
相关资源
最近更新 更多