偶然在一個老外的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.
菜鳥學堂:新聞熱點
疑難解答
圖片精選