Ayo Softech

Tuesday 21 November 2017

Passing values from Javascript to ASPX

you want to retrieve the variable from JavaScript in aspx page. I'm agreed with mcguzic. You can set the variable from JavaScript into Hidden control and then you can get it in aspx page.
HTML:
<script type="text/javascript">
function abc()
{
  var str="value";
  document.getElementById("Hidden1").value=str;
}


</script>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Hidden1" type="hidden" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClientClick="abc()"  Text="Button"
            onclick="Button1_Click" />
    </div>
    </form>
</body>
 Code Behind:
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Hidden1.Value);
    }
 But you should pay attention on the order of setting the variable to Hidden control in JavaScript and retrieving the value of Hidden control in aspx page. In the same event handle, it needs execute the Client first. For example,  OnClientClick="abc()" will be executed before onclick="Button1_Click". Otherwise, you will get the empty.
Hope it helps.