Are there any benefits to using HtmlTextWriter if you are not going to benefit from adaptive rendering?

后端 未结 5 1385
北恋
北恋 2021-02-07 11:17

Outside of benefiting from Adaptive Rendering for alternate devices, does it ever make sense to write all of this code:

writer.WriteBeginTag(\"t         


        
5条回答
  •  自闭症患者
    2021-02-07 11:54

    Another advantage could be that using HtmlTextWriter one could format code in a cleaner (more maintenance friendly) way, and that HtmlTextWriter supports encoding HTML automatically. Compare:

    writer.AddAttribute(HtmlTextWriterAttribute.Id, "someId");
    if (!string.IsNullOrEmpty(cssClass)) writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClass);
    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "Red");
    writer.RenderBeginTag(HtmlTextWriterTag.Span);
    writer.WriteEncodedText(text);
    writer.RenderEndTag();
    

    versus:

    StringBuilder html = new StringBuilder();
    html.Append("");
    html.Append(HttpUtility.HtmlEncode(text));
    html.Append("");
    

    One may argue that the code in the second example can be written in a different, possibly cleaner, way, but this could be seen as an advantage of HtmlTextWriter because it basically enforces one canonical way of formatting (which again improves maintenance).

    Edit: In fact, I actually made a mistake in the second snippet, and I needed to go back and fix the response. This confirms the point I wanted to make.

提交回复
热议问题