【導讀】本文講述了TextBox控件獲得數據的內部方法中ReadOnly的限制,使用實例說明了這一點,並且提供了既使用ReadOnly,又可以通過Text屬性獲得值的方法。
在以前的ASP.NET 1.x版本中,設置為ReadOnly的TextBox控件在客戶端更改了值後,在服務器端仍然可以得到修改後的值,但在ASP.NET 2.0中,這種做法已經限制。這是為了提高應用程序安全性所考慮的。下面就是TextBox控件獲得數據的內部方法,由此可以看出ReadOnly的限制:
protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
base.ValidateEvent(postDataKey);
string text1 = this.Text;
string text2 = postCollection[postDataKey];
if (!this.ReadOnly && !text1.Equals(text2, StringComparison.Ordinal))
{
this.Text = text2;
return true;
}
return false;
}
這裡限制的只是Text屬性,而沒有限制提交數據的名稱/值的NameValueCollection,因此,通過Request["表單名稱"]的方法仍然可以得到值的。下面的例子充分說明了這一點,並且提供了既使用ReadOnly,又可以通過Text屬性獲得值的方法:
<%@ Page Language="C#" EnableViewState="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("<li>TextBox1 = " + TextBox1.Text);
Response.Write("<li>TextBox2 = " + TextBox2.Text);
Response.Write("<li>TextBox3 = " + TextBox3.Text);
Response.Write("<li>Request.Form[TextBox1] = " + Request.Form[TextBox1.UniqueID]);
Response.Write("<li>Request.Form[TextBox2] = " + Request.Form[TextBox2.UniqueID]);
Response.Write("<li>Request.Form[TextBox3] = " + Request.Form[TextBox3.UniqueID]);
}
protected void Page_Load(object sender, EventArgs e)
{
TextBox3.Attributes.Add("readonly", "readonly");
}
</script>
<script type="text/javascript">
//<![CDATA[
function SetNewValue()
{
document.getElementById('<%=TextBox1.ClientID %>').value = "TextBox1 new Value";
document.getElementById('<%=TextBox2.ClientID %>').value = "TextBox2 new Value";
document.getElementById('<%=TextBox3.ClientID %>').value = "TextBox3 new Value";
}
//]]>
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET 2.0中TextBox控件與ReadOnly和Enabled屬性</title>
</head>
<body>
<form id="form1" runat="server">
<span>TextBox1 ReadOnly:</span>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True" Text="TextBox1 Old Value"></asp:TextBox><br />
<span>TextBox2 Enabled:</span>
<asp:TextBox ID="TextBox2" runat="server" Enabled="False" Text="TextBox2 Old Value"></asp:TextBox><br />
<span>TextBox3 ReadOnly:</span>
<asp:TextBox ID="TextBox3" runat="server" Text="TextBox3 Old Value"></asp:TextBox><br />
<br />
<asp:Button ID="Button2" runat="server" Text="修改新值" OnClientClick="SetNewValue();return false;" />
<asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
</form>
</body>
</html>