是的,你沒有看錯,確實是Hidden Field的值沒有PostBack到後台,我在百度和google上也沒有搜尋到相關內容.
尋找n遍無果,還以為是因為項目類型(類庫類型)的關係.直到有天偶然想到可能是指令碼事件onbeforeunload的問題.經測試,確實原因出在這.
【總結】
NameValueCollection在onbeforeunload事件執行前就已儲存好,所以在onbeforeunload事件中再更改input的值已不會起作用,反映到NameValueCollection中.
但是:如果使用到return onbeforeunload事件,則改變的值又會反映到NameValueCollection中,PostBack到後台.
【測試代碼】
前台代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<script language="javascript" type="text/javascript">
function ChangeHiddenValue()
{
document.getElementById("hidAX").value="已賦值!";
alert(document.getElementById("hidAX").value);
//加return,離開頁面時會顯示對話方塊,並且顯示return的內容
//return "Hello";
}
</script>
</head>
<body onbeforeunload="ChangeHiddenValue();">
<%--<body onbeforeunload="return ChangeHiddenValue();">--%>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="hidAX" runat="server" Value="預設值" />
<asp:Button ID="btnAX" runat="server" Text="點我進行PostBack" />
<%--<asp:Button ID="btnTest" runat="server" OnClientClick="ChangeHiddenValue();" Text="點我進行PostBack" />--%>
</div>
</form>
</body>
</html>
後台代碼:public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hidAX.Value);
}
}