问题
I have some JavaScript that sets the value of a HiddenField
and then forces a postback. I can trace through this JavaScript and it appears to work correctly. However, when I test the value of the HiddenField
from the page's Load event, it is no longer set.
Searching the web, I see a lot of posts about losing HiddenField
values but none of them seemed to be doing the same thing that I am.
Here's my JavaScript function (modified):
function EditItemItem(itemId) {
document.getElementById('<%= EditItemId.ClientID %>').value = itemId;
__doPostBack('<%= EditItemUpdatePanel.ClientID %>', '');
}
And here's part of my markup (modified):
<div id="EditItemBox" runat="server">
<asp:HiddenField runat="server" id="EditItemId" />
<asp:UpdatePanel ID="EditItemUpdatePanel" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="EditItemPanel" runat="server"
CssClass="ModalDialog" style="display:none;">
<div>Edit an Item</div>
<!-- ... -->
</asp:Panel>
</asp:UpdatePanel>
</div>
Does anyone have any ideas?
回答1:
It's easier if you remove runat=server
from the hidden field and then access it from the Form paramaters Request.Form["EditItemId"]
. Then it works every time.
Your code will become:
function EditItemItem(itemId) {
document.getElementById('EditItemId').value = itemId;
__doPostBack('<%= EditItemUpdatePanel.ClientID %>', '');
}
<div id="EditItemBox" runat="server">
<input type="hidden" id="EditItemId" name="EditItemId" value="" />
<asp:UpdatePanel ID="EditItemUpdatePanel" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="EditItemPanel" runat="server"
CssClass="ModalDialog" style="display:none;">
<div>Edit an Item</div>
<!-- ... -->
</asp:Panel>
</asp:UpdatePanel>
</div>
回答2:
If you're expecting the value upon an AJAX post-back via the UpdatePanel
then you need to put it inside the ContentTemplate
...
来源:https://stackoverflow.com/questions/6349155/hiddenfield-value-lost-on-postback