Search code examples
asp.nethidden-field

Hidden Field looses it's value before/when submit button pushed


I'm using ASP.NEt hiddenfield in a form:

 <form id="form1" runat="server">       

        <asp:HiddenField ID="ScreenWidth"  runat="server"  />
        <asp:HiddenField ID="ScreenHeight" runat="server" />

     <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>

This is the JS code:

<script type="text/javascript">
$(document).ready(function() {
    alert(document.getElementById("ScreenWidth").val);
    document.getElementById("ScreenWidth").val = screen.width;
    document.getElementById("ScreenHeight").val = screen.height;
     alert(document.getElementById("ScreenWidth").val);

    });

but when I access the values on the onsubmit function - they are empty. The alert shows un-defined and then a value when fired - so the JS. part works...

How can I get the values in the c# code ?

  myheight = ScreenHeight.Value.ToString();
    mywidth = ScreenWidth.Value.ToString();

Solution

  • Use toString(); in the js:

    document.getElementById("hidScreenWidth").value = screen.width.toString();
    

    Code-behind:

    string w = hidScreenWidth.Value;