I’d like to encapsulate some HTML-creation logic (e.g. for eventual usage in an ASP.NET MVC razor page). Can I do this with a structured API in plain C#?
I’d like to avoid error-prone string-based constructions where I manually need to build tags and escape the right strings since that strikes me as much harder to maintain and likely to result in html-injection vulnerabilities. Something like the XElement API (for instance), but then for html generation: an API that takes care of well-formedness at minimum and avoids boilerplate.
Does such an API exist? What’s the best way to generate html fragments safely and easily?
There is a built in HTML generator in ASP.NET MVC. It’s called TagBuilder and it is used internally by all the built in Html helpers.
For example generating the following HTML:
Looks like:
In our projects we usually create a thin fluid wrapper around the
TagBuildersomething like this one to make the it’s API a little bit more fluid.If it’s ok to use some thrid party libraries and you need some advanced features you can have a look on: