blob: c9e5c117aacb4ef9745300e225e503ae4768bccb (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Web.UI;
namespace System.Web.Helpers
{
internal class HtmlElement
{
public HtmlElement(string tagName)
{
TagName = tagName;
Attributes = new Dictionary<string, string>();
Children = new List<HtmlElement>();
}
internal string TagName { get; set; }
internal string InnerText { get; set; }
public IList<HtmlElement> Children { get; set; }
private IDictionary<string, string> Attributes { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "It is there for completeness")]
public string this[string name]
{
get { return Attributes[name]; }
set { MergeAttribute(name, value); }
}
public HtmlElement SetInnerText(string innerText)
{
InnerText = innerText;
Children.Clear();
return this;
}
public HtmlElement AppendChild(HtmlElement e)
{
Children.Add(e);
return this;
}
public HtmlElement AppendChild(string innerText)
{
AppendChild(CreateSpan(innerText));
return this;
}
private void MergeAttribute(string name, string value)
{
Attributes[name] = value;
}
public HtmlElement AddCssClass(string className)
{
string currentValue;
if (!Attributes.TryGetValue("class", out currentValue))
{
Attributes["class"] = className;
}
else
{
Attributes["class"] = currentValue + " " + className;
}
return this;
}
public IHtmlString ToHtmlString()
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
WriteTo(sw);
return new HtmlString(sw.ToString());
}
}
public void WriteTo(TextWriter writer)
{
WriteToInternal(new HtmlTextWriter(writer));
}
private void WriteToInternal(HtmlTextWriter writer)
{
foreach (var a in Attributes)
{
writer.AddAttribute(a.Key, a.Value, true);
}
writer.RenderBeginTag(TagName);
if (!String.IsNullOrEmpty(InnerText))
{
writer.WriteEncodedText(InnerText);
}
else
{
foreach (var e in Children)
{
e.WriteToInternal(writer);
}
}
writer.RenderEndTag();
}
public override string ToString()
{
return ToHtmlString().ToString();
}
internal static HtmlElement CreateSpan(string innerText, string cssClass = null)
{
var span = new HtmlElement("span");
span.SetInnerText(innerText);
if (!String.IsNullOrEmpty(cssClass))
{
span.AddCssClass(cssClass);
}
return span;
}
}
}
|