Jonathan Wood
Jonathan Wood

Reputation: 67195

HiddenField Value Lost on Postback

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?

Upvotes: 2

Views: 11178

Answers (2)

marto
marto

Reputation: 4170

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>

Upvotes: 6

Kieron
Kieron

Reputation: 27107

If you're expecting the value upon an AJAX post-back via the UpdatePanel then you need to put it inside the ContentTemplate...

Upvotes: 1

Related Questions