user1468537
user1468537

Reputation: 703

asp.net passing values from JS/jquery to code behind c#

I have tried "every" possible way of sending the screen.width vlaue from the JS script on the aspx page to the c# in the code behind and while I can see the screen.width being assigned correctly it never gets assigned to my hidden field value.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

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

   <script type="text/javascript" language="javascript">
       $(function(){ 
       $('#hiddenfield').val(screen.width); 
    });
    </script>

other content

</asp:Content>

and the code behind:

protected void btnChartGo_Click(object sender, EventArgs e)
{
   string s = hiddenfield.Value;
}

No matter what I try s is always ""

Something wrong with the above, everyone seems to be doing it like that and it works?

Upvotes: 2

Views: 6923

Answers (4)

Dave
Dave

Reputation: 3621

The ID of the rendered hidden field isn't "hiddenfield" - it'll be something like ctl00_bodycontent_hiddenfield.

Try using

$('[id$="hiddenfield"]') 

as the selector instead.

Upvotes: 2

DSharper
DSharper

Reputation: 3217

<asp:HiddenField ID="hiddenfield" runat="server" ClientIDMode="Static">
</asp:HiddenField >

Make sure client ID mode of your hidden field is static if you are using ASP.NET 4 or use

$('#<%= hiddenfield.ClientID %>').val(screen.width); 

Upvotes: 1

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

Check the view source of the page and find out proper id of the element and then use jquery selector over it and then at the page load check for request.form collection to check if hidden variable is coming in post request or not

Upvotes: 0

RemarkLima
RemarkLima

Reputation: 12037

This should get the right selector:

$('#<%= hiddenfield.ClientID %>').val(screen.width); 

Upvotes: 0

Related Questions