Saturday, 6 October 2012

JavaScript: How to use javascript variables in ASP.NET C# and vise versa

1.         Passing values from C# Code Behind to JavaScript.
You can use <%=variable%> to get value from aspx.cs. Variable must be public in aspx.cs file.
For example, you can use: var date=”<%=DateTime.Now%>”;  to get the server time.
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.

No comments:

Post a Comment