10

I can't set the value of a hidden field with jquery in asp .net.

My hidden field is declared like this:

<asp:HiddenField runat="server" ID="hdnSelectedTicket" />

And this is how I set the value:

            alert(ticketID);
            $('#<%=hdnSelectedTicket.ClientID %>').val(ticketID);
            alert($('#<%=hdnSelectedTicket.ClientID %>').val());

Both alerts show the right value but when I fetch it at the server it is empty.

3
  • 2
    Everything looks ok on that code, what about the code behind ? - maybe there is the issue ? Commented Jun 26, 2013 at 12:01
  • What does your server side code look like when you're retrieving the value? Commented Jun 26, 2013 at 12:07
  • I access it like this: string.IsNullOrEmpty(hdnSelectedTicket.Value). And when check the value it is an empty string Commented Jun 26, 2013 at 12:12

3 Answers 3

20

Set ClientIDMode="Static" and then you can use $('#hdnSelectedTicket').val(ticketID); to set the value in asp hidden field

like

asp:HiddenField ID="hdnSelectedTicket" runat="server" ClientIDMode="Static"

and

$('#hdnSelectedTicket').val(ticketID);
Sign up to request clarification or add additional context in comments.

Comments

7

It turns out that I was putting the hidden field inside a div that was used as a model for jquery dialog. When I removed the hidden field from the div and place it somewhere else it worked.

2 Comments

Thanks for posting this. This was the answer to my problem as well!
As long as the field is within the <form> tag, it should be returned properly.
3

Depending when you are reading the value on the server side, it might not be updated on the control yet - essentially if you are doing it in a change event handler, and the control that raises the change event gets updated before the hidden control, then calling hdnSelectedTicket.Value can still return the old value.

The easiest way to get around this issue is to cheat and get it straight from the Form collection:

var ticketId = Request.Form[hdnSelectedTicket.UniqueID];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.