Castaldi Castaldi - 3 months ago 14
C# Question

Adding missing html tags

Is it possible to add missing html tags in ASP MVC. Here is what I mean:

String x = "<p><b>Hello world how are you</b></p>";


Substing of that string at the first few character would result in:

String x = "<p>Hello world ";


Where there is the
</p>
tag missing, using
@MvcHtmlString.Create(x)
in a loop will cause a confusion of tags cause of the missing tags.

Is there a method in ASP MVC to do this automatically or a C# function to correct them?

Answer

Check this gist: https://gist.github.com/mouhong/c09487502e261f7ce53d

It will close missing end tags (supports nested tags) and broken end tags, and will ignore broken start tags.

It's not fully tested, let me know if you find any bug :P

Usage:

"<p>Hello".CloseTags();

Examples:

+-------------------------+--------------------------------+
|            Input        |          Output                |
+-------------------------+--------------------------------+
| <div>Hello World        | <div>Hello World</div>         |
| <div>Hello, <b>World    | <div>Hello, <b>World</b></div> |
| <div>Hello World</di    | <div>Hello World</div>         |
| <div>Hello, <b>World</  | <div>Hello, <b>World</b></div> |
| <div>Hello World. <span | <div>Hello World. </div>       |
+-------------------------+--------------------------------+