Print inner text of a HtmlContent in a razor view (MVC4)

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.

Answers


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.


Need Your Help

Preventing GTKMM from catching exceptions

c++ gtkmm

Is there a way to prevent 'Gtk::Main::iteration()' from catching exceptions?

Style for wrapped text with spreadsheetml

xml excel xslt spreadsheetml

I generate my spreadsheet with xslt and want a cell with wrapped text (or better: a text with a line break in it).