Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if HtmlString is whitespace in C#

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!

like image 643
AnimaSola Avatar asked Feb 06 '14 03:02

AnimaSola


2 Answers

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!

like image 134
AnimaSola Avatar answered Oct 21 '22 15:10

AnimaSola


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);
like image 6
noseratio Avatar answered Oct 21 '22 15:10

noseratio