我一直在嘗試通過使用Javascript設置隱藏輸入的值,然後從我的C#代碼隱藏中訪問值。當我運行下面複製的代碼時,分配給assignedID的值爲「」,我假設它是隱藏輸入的默認值。如果我手動設置了html標籤中的值,那麼分配的ID被設置爲該值。在Javascript中設置隱藏的輸入值,然後在代碼隱藏中訪問它
此行爲向我建議,onClientClick和onClick事件觸發之間的輸入值正在重置(重新呈現?)。
我將不勝感激任何幫助。我花了幾個小時試圖解決看起來像一個非常簡單的問題。
HTML/JavaScript的:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Page - Manage Tasks</title>
<script language="javascript" type="text/javascript">
function PopulateAssignedIDHiddenInput() {
var source = document.getElementById('assignedLinguistListBox');
var s = "";
var count = source.length;
for (var i = count - 1; i >= 0; i--) {
var item = source.options[i];
if (s == "") { s = source.options[i].value; }
else { s = s.concat(",",source.options[i].value); }
}
document.getElementById('assignedIDHiddenInput').Value = s;
// I have confirmed that, at this point, the value of
// the hidden input is set properly
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="EditMode" runat="server">
<table style="border: none;">
<tr>
<td>
<asp:Label ID="availableLinguistLabel" runat="server" Text="Available"></asp:Label><br />
<asp:ListBox ID="availableLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
<td>
<input type="button" name="right" value=">>"
onclick="Javascript:MoveItem('availableLinguistListBox', 'assignedLinguistListBox');" /><br /><br />
<input type="button" name="left" value="<<"
onclick="Javascript:MoveItem('assignedLinguistListBox', 'availableLinguistListBox');" />
</td>
<td>
<asp:Label ID="assignedLinguistLabel" runat="server" Text="Assigned To"></asp:Label><br />
<asp:ListBox ID="assignedLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
</tr>
</table>
//-snip-
<asp:Button ID="save_task_changes_button" runat="server" ToolTip="Click to save changes to task"
Text="Save Changes" OnClick="save_task_changes_button_click" OnClientClick="Javascript:PopulateAssignedIDHiddenInput()" />
</asp:Panel>
<!-- Hidden Inputs -->
<!-- Note that I have also tried setting runat="server" with no change -->
<input id="assignedIDHiddenInput" name="assignedIDHiddenInput" type="hidden" />
</div>
</form>
</body>
C#
protected void save_task_changes_button_click(object sender, EventArgs e)
{
string assignedIDs = Request.Form["assignedIDHiddenInput"];
// Here, assignedIDs == ""; also, Request.Params["assignedIDHiddenInput"] == ""
// -snip-
}
哦......哇。我無法相信!這樣一個愚蠢而簡單的錯誤。謝謝你,尼克! – Siegesmith 2010-04-21 22:44:57
使用'for ... in'語句對'options' ['HTMLOptionsCollection'](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#HTMLOptionsCollection)對象進行迭代給你真正意想不到的結果,在一些瀏覽器中,即使數字選項索引不會被迭代,我會推薦一個普通的'for'循環,檢查[這個例子](http://jsbin.com/ohebe/)。 – CMS 2010-04-21 23:46:26
@CMS - 瀏覽器依賴關係上的重點,也習慣於這裏的每個關閉。我更新了上面的代碼,以防其他人在稍後遇到此問題需要相同的信息。 – 2010-04-22 00:47:21