简体   繁体   中英

Populate asp hidden field with value using javascript

I want to access user screen resolution from server side. For this I have asp hidden control:

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

Which actually rendering on page:

<input type="hidden" name="ctl00$MainContent$hdnScreenResolution" id="MainContent_hdnScreenResolution" />

I use javascript function to insert value in it:

$(document).ready(function () {
   var width = screen.width;
   var height = screen.height;

   var hiddenScreenResolution = document.getElementById('<%= hdnScreenResolution.ClientID
    %>'); 
   hiddenScreenResolution.value = "asass";
});

And it is on page source code:

       $(document).ready(function () {
            var width = screen.width;
            var height = screen.height;

            var hiddenScreenResolution = document.getElementById('MainContent_hdnScreenResolution'); 
            hiddenScreenResolution.value = "asass";
        });

On server side I check hidden value on Page_Load() :

protected void Page_Load(object sender, EventArgs e)
{
    var hiddenValue = hdnScreenResolution.Value;
}

But value appears to be empty string. Using jquery does not help.

Inserting directly: document.getElementById('<%= hdnScreenResolution.ClientID %>').value = "asdasd"; does not help.

What the problem can be?

PS I suppose that I catching screen resolution on document.ready is too late. And javascript fires after page was unloaded. So no change to catch it on initial request.

Looking forward for an answer.

The server side Page_Load is called before the html is sent to client and execution of jQuery document.ready so you are accessing value before assigning on client using javascript and you should get empty.

You need to send values from client to server, you can use jQuery ajax for do postback for getting screen coordinates values on server.

To see what is happening just add asp:button and access hidden field values in its server side event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM