How to build HTML from code in C #

I need to create an HtmlHelper in my MVC application that displays some nested and rather complex UL / LI (tree) structures. The HtmlTextWriter and XmlTestWriter provide tools for creating proper HTML, but they are advanced, which makes my work quite difficult, because after you provide the tag, you don’t have a link to the “parent” tag.

XDocument and XElement were the next candidates that I looked at, but they were created for XML, not HTML, which could lead to invalid HTML (self-closing tags, etc.).

How can i do this?

This alleged duplicate is not really a duplicate and does not answer my question at all. It's about creating an HTML-Helper rendering of one Html tag. This is not what I want. I would like to know how to build a whole DOM in C # code.

+6
source share
2 answers

I wanted to do something similar before, and ended up playing with an object structure that would represent elements, such as the server-side DOM, that could be processed in code before rendering in HTML.

Others did similar things. Well-known examples are SharpDOM: http://www.codeproject.com/Articles/667581/SharpDOM-a-new-view-engine-for-ASP-NET-MVC and CityLizard: https://citylizard.codeplex.com/

These days, I tend to create a View Model that deals with most of the logic and manipulates how the view looks and then renders it.

You may also find partial views (called recursively) a useful approach.

0
source

If I wanted to do this, I would do it like this (simplified):

Item class

  public class HtmlListItem { public string Content { get; set; } public object HtmlAttributes { get; set; } } 

Html helper

  public HtmlString RenderList(this HtmlHelper htmlHelper, IEnumerable<HtmlListItem> list, object uListHtmlAttributes) { TagBuilder ul = new Tagbuilder("ul"); IDictionary<string, object> uListAttributes = new RouteValueDictionary(uListHtmlAttributes); ul.MergeAttributes(uListAttributes); StringBuilder builder = new StringBuilder(); builder.Append(ul.ToString(TagRenderMode.StartTag) + Environment.NewLine); foreach (var item in list) { TagBuilder hold = new TagBuilder("li"); IDictionary<string, object> htmlAttributes = new RouteValueDictionary(item.HtmlAttributes); hold.MergeAttributes(htmlAttributes); hold.InnerHtml = item.Content; builder.Append(hold.ToString(TagRenderMode.Normal) + Environment.NewLine); } builder.Append("</ul>" + Environment.NewLine); return new HtmlString(builder.ToString()); } 
0
source

Source: https://habr.com/ru/post/987118/


All Articles