Check if HtmlString is whitespace in C#

asp.net-mvc, c#, html, string, whitespace

Solution

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);

Problem

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>&nbsp; &nbsp;</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!

Original source