I've got a wrapper that adds a header to a field whenever it has a value. The field is actually a string which holds HTML from a tinymce textbox.
Requirement: the header should not display when the field is empty or just whitespace.
Issue: whitespace in html is rendered as <p> </p>
, so technically it's not an empty or whitespace value
I simply can't !String.IsNullOrWhiteSpace(Model.ContentField.Value)
because it does have a value, albeit whitespace html.
I've tried to convert the value onto @Html.Raw(Model.ContentField.Value)
but it's of a type HtmlString, so I can't use String.IsNullOrWhiteSpace
.
Any ideas? Thanks!
What I eventually did (because I didn't want to add a 3rd party library just for this), is to add a function in a helper class that strips HTML tags:
const string HTML_TAG_PATTERN = "<.*?>";
public static string StripHTML(string inputString)
{
return Regex.Replace
(inputString, HTML_TAG_PATTERN, string.Empty);
}
After which, I combined that with HttpUtility.HtmlDecode
to get the inner value:
var innerContent = StringHelper.StripHTML(HttpUtility.HtmlDecode(Model.ContentField.Value));
That variable is what I used to compare. Let me know if this is a bad idea.
Thanks!
You can use HtmlAgilityPack
, something like this:
HtmlDocument document = new HtmlDocument();
document.LoadHtml(Model.ContentField.Value);
string textValue = HtmlEntity.DeEntitize(document.DocumentNode.InnerText);
bool isEmpty = String.IsNullOrWhiteSpace(textValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With