5.10 处理DropDownList控件
问题
如何发送一个HTTP请求表示DropDownList控件的某个值被选中。
设计
修改POST数据字符串,让这个字符串包含你想要操控的DropDownList控件的ID以及被选中的值。
方案
string url = "http://server/path/WebForm.aspx";
string data = "DropDownList1=SomeOption";
string viewstate = HttpUtility.UrlEncode("dDwtMTQ2MzgwNTQ2MD==");
data += "&__VIEWSTATE=" + viewstate;
// 把数据发送到Web应用程序
注解
ASP.NET Web程序中,常见的一种控件是DropDownList控件。例如,设想你有如下程序:
<html>
<head>
<script language="c#" runat="server">
void Button1_Click(object sender, System.EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue;
}
</script>
</head>
<body>
<h3>DropDownList</h3>
<form id="Form1" method="post" runat="server">
<p>Choose one:
<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Value="ant">ant</asp:ListItem>
<asp:ListItem Value="bug">bug</asp:ListItem>
<asp:ListItem Value="cat">cat</asp:ListItem>
</asp:DropDownList>
<p><asp:Button id="Button1" text="Send" onclick="Button1_Click"
runat="server" />
<p>You chose:
<p><asp:TextBox id="TextBox1" runat="server" /></p>
</form>
</body>
</html>
这个程序抓取DropDownList1控件中被选中的值并把它显示在TextBox1里。要在程序中发送一个对应于DropDownList1中“bug”被选中的HTTP请求,可以像下面这样准备好一个POST数据字符串:
string data = "DropDownList1=bug&TextBox1=empty";
data += "&Button1=clicked";
如果把上述数据提交给待测Web程序,对应的HTTP响应会包含以下数据:
<p>You chose:
<p><input name="TextBox1" type="text" value="bug"
id="TextBox1" /></p>







