ASP.NET XML 數(shù)據(jù)綁定

2022-02-08 17:46 更新

ASP.NET Web Forms - XML 文件

在 ASP.NET 中可以通過將 XML 文件當(dāng)成數(shù)據(jù)源來將它綁定到 List 控件上。請參考本節(jié)內(nèi)容。

我們可以綁定 XML 文件到列表控件。


一個(gè) XML 文件

這里有一個(gè)名為 "countries.xml" 的 XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>

<countries>

<country>
<text>Norway</text>
<value>N</value>
</country>

<country>
<text>Sweden</text>
<value>S</value>
</country>

<country>
<text>France</text>
<value>F</value>
</country>

<country>
<text>Italy</text>
<value>I</value>
</country>

</countries>

查看這個(gè) XML 文件:countries.xml


綁定 DataSet 到 List 控件

首先,導(dǎo)入 "System.Data" 命名空間。我們需要該命名空間與 DataSet 對象一起工作。把下面這條指令包含在 .aspx 頁面的頂部:

<%@ Import Namespace="System.Data" %>

接著,為 XML 文件創(chuàng)建一個(gè) DataSet,并在頁面第一次加載時(shí)把這個(gè) XML 文件載入 DataSet:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub

為了綁定數(shù)據(jù)到 RadioButtonList 控件,首先要在 .aspx 頁面中創(chuàng)建一個(gè) RadioButtonList 控件(不帶任何 asp:ListItem 元素):

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>

然后添加創(chuàng)建 XML DataSet 的腳本,并且綁定 XML DataSet 中的值到 RadioButtonList 控件:

<%@ Import Namespace="System.Data" %>

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
rb.DataSource=mycountries
rb.DataValueField="value"
rb.DataTextField="text"
rb.DataBind()
end if
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
</form>

</body>
</html>

然后我們添加一個(gè)子例程,當(dāng)用戶點(diǎn)擊 RadioButtonList 控件中的某個(gè)項(xiàng)目時(shí),該子例程會被執(zhí)行。當(dāng)某個(gè)單選按鈕被點(diǎn)擊時(shí),label 中會出現(xiàn)一行文本:

實(shí)例

<%@ Import Namespace="System.Data" %>

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
rb.DataSource=mycountries
rb.DataValueField="value"
rb.DataTextField="text"
rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>

</body>
</html>

以上就是關(guān)于 ASP.NET XML 數(shù)據(jù)綁定的介紹內(nèi)容。

相關(guān)教程

XML教程

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號