Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
How to pass variable from JavaScript to C# in asp.net at page load
I use a hidden field but it will give me null on page load but the value i get it when i use on click button.
but i need to get the value at c# at on-load time without using buttons or any user action..

I use this
XML
at JavaScript

    <script>SetHiddenVariable()</script>
    <script type="text/javascript">
        function SetHiddenVariable() {
            var jsVar = "dotnetcurry.com";

            var hiddenControl = '<%= inpHide.ClientID %>';
        document.getElementById(hiddenControl).value = jsVar;
    }
    </script>

---------------------------------------------
at html form

 <input id="inpHide" type="hidden" runat="server" />
        <asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
        <asp:Button ID="btnJSValue" Text="Click to retreive Javascript Variable" runat="server" onclick="btnJSValue_Click"/>

-----------------------------------------

at c#

   protected void btnJSValue_Click(object sender, EventArgs e)
        {
            txtJSValue.Text = inpHide.Value;
        }

I need the data passing without onclick function....

thanks
Posted
Comments
BacchusBeale 17-May-15 3:00am    
look here https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.value(v=vs.110).aspx.

1 solution

The problem is that the Load event happens at several times: once when the page is first requested and subsequently when the user interacts with it in such a way as to cause a post back to the server. A button click for example.

But...in the first case, when the page is first requested, the Javascript code is not executed until the page is loaded - which is after the Load event has occurred. So when the Load happens, there is no value in the hidden field because the page has not been rendered yet, other than that you put in there when you designed the page.

There is only a different value after the page has been fully rendered, and that means after a postback has occurred.
 
Share this answer
 
Comments
Hind Fakhri 17-May-15 7:19am    
Yes I understand that, so i try to postback the page but also i get null value. Can you please give me any suggestion to sent data to server side before rendering the page because want the page to be render depending on user choice from previous page and this choice go to server side to render the new page
function SetHiddenField() {
var vv = "HELLO WORLD";
document.getElementById('HiddenField').value = vv;
__doPostBack('<%=HiddenField.ClientID%>', '')

}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900