偶然在一个老外的blog里看到有这样的描述,当textbox控件里被设置为readonly时,而且页面的enableviewsate设置为false时,提交后,textbox的值会丢失,这只发生在asp.net 2.0中,在asp.net 1.0/1.1中不会出现这样的情况,代码如下:
<%@ page language=”c#” autoeventwireup=”true” codefile=”default.aspx.cs” enableviewstate=”false” inherits=”_default” %>
<!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 page_load(object sender, eventargs e)
{
if (!this.ispostback)
{
this.textbox1.text = “readonly text”;
}
}
protected void button1_click(object sender, eventargs e)
{
this.lblmessage.text = this.textbox1.text;
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title>untitled page</title>
</head>
<body>
<form runat=”server” id=”form1″>
<asp:textbox id=”textbox1″ runat=”server” readonly=”true” forecolor=”silver”></asp:textbox>
<asp:textbox id=”textbox2″ runat=”server” readonly=”true”>some text</asp:textbox>
<asp:button id=”button1″ runat=”server” text=”button” onclick=”button1_click” /><br />
<asp:label id=”lblmessage” runat=”server” text=”label”></asp:label>
</form>
</body>
</html>
在.net 2.0下运行,的确会丢失了文本框的值。最后,找到了msdn的解析和微软的bug反馈中心,其实这不是bug,是.net 2.0下为了安全的一个小改变,具体摘录如下,大家就明白了:
微软的反馈为:
after careful analysis, the explanation for the observed behaviour is that:
with a design change in asp .net based on user security concern, the input for a readonly textbox is saved in viewstate, which doesnt happen if viewstate is disabled. to workaround this, a page developer can add the readonly attribute to the textbox.attributes collection, which can then be used to access the value of the textbox.
we hope this clarifies. thank you.
web server & tools
msdn 2005的解析:
the text value of a textbox control with the readonly property set to true is sent to the server when a postback occurs, but the server does no processing for a read-only text box. this prevents a malicious user from changing a text value that is read-only. the value of the text property is preserved in the view state between postbacks unless modified by server-side code.