HTML.TextAreaFor - removing html tags for display only

2020-05-21 html css asp.net-mvc

In an MVC application I have to use @HTML.TextAreaFor to display some text from a database, the trouble is sometimes that text may have HTML tags within it and I can't see a way to remove those for display only.

Is it possible to do this in the view (maybe with CSS?) without having to strip the tags in the controller first?

EDIT

The data coming from the controller contains html tags which I do not want to remove, I just don't want to display them

Normally I would use @HTML.Raw but it has to work in a @HTML.TextAreaFor control.

Answers

If you want to decode Html returned from the Controller you can use the following JavaScript method:

This method decodes "Chris' corner" to "Chris' corner".

var decodeEntities = (function () {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');

function decodeHTMLEntities(str) {
    if (str && typeof str === 'string') {
        // strip script/html tags
        str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
        str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
        element.innerHTML = str;
        str = element.textContent;
        element.textContent = '';
    }
    return str;
}
return decodeHTMLEntities;
})(); 

You can do this by using a razor code in your view.

@Html.Raw(HttpUtility.HtmlDecode(Model.Content))

if I set Model.Content to this string "<strong>This is me</strong><button>click</button>", the code above will render it like HTML code and will have a strong text next to a button as an output like the image below:

enter image description here

There's some nice rich text editors libraries like CK Editor, Quill, or TinyMCE that can display HTML while still maintaining the editor capabilities of being a text editor. All of these libraries have capabilities of being read-only as well if that's necessary.

Example from Quill -

enter image description here

Sorted this by changing TextAreaFor toTextBoxFor and setting a formatted value.

@Html.TextBoxFor(x => Model.MyItem, new { @class = "form-control", @required = "true", Value = Regex.Replace(Model.MyItem, "<.*?>", String.Empty) })

Related