Question

Using MVC, look at this example where we have the following HTML code:

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

I would like that print only the content of the tags, as: Duma Duma, removing the image, tags and showing only the text (as innerText)

I tried using Html.Raw() but it's not worked. Also I was reading about the class TabBuilder and creating a Html extension method, but I don't have idea about how to implemeted in my razor view.

Était-ce utile?

La solution

You could make a string extension to strip the Html tags.

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

Then use it in your view

@myHtmlString.StripHtml()

You might need to declaring a using statement for the StringExtensions class or add it to the Web.Config file in your Views folder

@using My.Extensions.Namespace

OR

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

You could also make a 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);
    }
}

You can use this in your view like this

@Html.StripHtml(myHtmlString)

You will still need to add a reference to the namespace for your extension methods like above. Either adding to your Web.Config in your Views folder or adding a using statement in your view. The differences here is that adding it to your Web.Config file you will be able to use this extension method in all your views without adding the using statement.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top