0

使用 MVC,看看这个例子,我们有以下 HTML 代码:

<p>Duma</p><img url='..' /><p>Duma</p>

我希望只打印标签的内容,如:Duma Duma,删除图像,标签并仅显示文本(作为 innerText)

我尝试使用 Html.Raw() 但它不起作用。我也在阅读该类TabBuilder并创建一个 Html 扩展方法,但我不知道如何在我的剃刀视图中实现。

4

1 回答 1

2

您可以制作一个字符串扩展名来去除 Html 标记。

public static class StringExtensions
{
    public static string StripHtml (this string inputString)
    {
       return Regex.Replace 
         (inputString, "<.*?>", string.Empty);
    }
}

然后在你的视图中使用它

@myHtmlString.StripHtml()

您可能需要为 StringExtensions 类声明 using 语句或将其添加到 Views 文件夹中的 Web.Config 文件中

@using My.Extensions.Namespace

或者

<system.web>
    <pages>
      <namespaces>
        <add namespace="My.Extensions.Namespace" />
      </namespaces>
    </pages>
</system.web>

你也可以制作一个 Html Helper Extension

public static class HtmlExtensions
{
    public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
    {
       return Regex.Replace 
         (htmlString, "<.*?>", string.Empty);
    }
}

您可以像这样在您的视图中使用它

@Html.StripHtml(myHtmlString)

您仍然需要为上述扩展方法添加对命名空间的引用。在 Views 文件夹中添加到 Web.Config 或在视图中添加 using 语句。这里的不同之处在于,将其添加到您的 Web.Config 文件中,您将能够在所有视图中使用此扩展方法,而无需添加 using 语句。

于 2013-05-02T19:18:45.983 回答