ASP.NET批量操作基于原生html标签的无序列表的三种方法

时间:2021-10-23 13:27:38

在网页开发中,经常要用到无序列表。事实上在符合W3C标准的div+css布局中,无序列表被大量使用,ASP.NET虽然内置了BulletedList控件,用于创建和操作无序列表,但感觉不太好用。本篇介绍服务器端ASP.NET批量操作基于原生html标签的无序列表的三种方法。

方法一,将li元素做成html控件,加上id,用FindControl方法。

aspx代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<form id="form1" runat="server">
<ul>
<li id="li1" runat="server">初始值1</li>
<li id="li2" runat="server">初始值2</li>
<li id="li3" runat="server">初始值3</li>
<li id="li4" runat="server">初始值4</li>
<li id="li5" runat="server">初始值5</li>
<li id="li6" runat="server">初始值6</li>
<li id="li7" runat="server">初始值7</li>
<li id="li8" runat="server">初始值8</li>
</ul>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>

aspx.cs代码:

?
1
2
3
4
5
6
7
8
9
10
protected void Button1_Click(object sender, EventArgs e)
{
//单击按钮后批量改变li元素的内联文本值及样式
for (int i = 1; i <= 8; i++)
{
HtmlGenericControl li = this.FindControl("li" + i) as HtmlGenericControl;
li.InnerHtml = "新值" + i.ToString();
li.Attributes.CssStyle.Value = "color:red";
}
}

方法二,将ul、li元素做成html控件,用ul控件的Controls集合遍历。

aspx代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<form id="form1" runat="server">
<ul id="ul1" runat="server">
<li runat="server">初始值1</li>
<li runat="server">初始值2</li>
<li runat="server">初始值3</li>
<li runat="server">初始值4</li>
<li runat="server">初始值5</li>
<li runat="server">初始值6</li>
<li runat="server">初始值7</li>
<li runat="server">初始值8</li>
</ul>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>

aspx.cs代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private int counter = 1;
protected void Button1_Click(object sender, EventArgs e)
{
//单击按钮后批量改变li元素的内联文本值及样式
foreach (Control control in ul1.Controls)
{
if (control is HtmlGenericControl)
{
HtmlGenericControl li = control as HtmlGenericControl;
li.InnerHtml = "新值" + (counter++).ToString();
li.Attributes.CssStyle.Value = "color:red";
}
}
}

方法三,利用HtmlAgilityPack,对元素以Dom方式操作。

aspx代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<form id="form1" runat="server">
<ul id="ul1" runat="server">
<li>初始值1</li>
<li>初始值2</li>
<li>初始值3</li>
<li>初始值4</li>
<li>初始值5</li>
<li>初始值6</li>
<li>初始值7</li>
<li>初始值8</li>
</ul>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="测试空回发" />
</form>

aspx.cs代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
protected void Button1_Click(object sender, EventArgs e)
{
//单击按钮后批量改变li元素的内联文本值及样式
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(ul1.InnerHtml);
HtmlNodeCollection lis = htmlDoc.DocumentNode.SelectNodes("li");
for (int i = 0; i < lis.Count; i++)
{
lis[i].InnerHtml = "新值" + (i + 1).ToString();
lis[i].Attributes.Add("style", "color:red");
}
ul1.InnerHtml = htmlDoc.DocumentNode.InnerHtml;
}

以上三种方法各有优缺点,可根据实际情况选用。