How to Pass value from ASP.Net to Javascript

Many times we have to pass a value from server side (ASP.Net) to client side (java script) and many peoples ask this question that how we can accomplish this task. Here I am sharing some examples in which I will tell different approaches to send values from ASP.Net to javascript.

1- <%=%> Construct
You can simply use a <%=%> construct to pass server side variable to client side. Here is how you can do this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var myVariable = '<%=ServerSideVariable %>';
    alert(myVariable);
</script>

Here is the server side code in which I assigned value to my variable:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    public string ServerSideVariable { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        ServerSideVariable = "Zeeshan Umar";
    }
}

Here is the output when I run the page, a popup appears saying 'Zeeshan Umar'.

2) Hidden Field
You can also use hidden fields to store values which can be used in javascript here is how you can do this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="hfValueFromServer" runat="server" />
    </div>
    </form>
</body>
</html>
<script type="text/javascript">
    var valueFromServer= document.getElementById('<%=hfValueFromServer.ClientID%>').value;
    alert(valueFromServer);
</script>

Here is the server side code in which I assigned value to hidden field:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        hfValueFromServer.Value = "Zeeshan Umar javascript tutorial";
    }
}

And here is the output of above code, same as expected 'Zeeshan Umar javascript tutorial':-

See how simple is it to access server side variables in javascript. Do share me with your valuable feedback and comments. Happy coding !!

1 comment:

  1. Hi. I
    was considering adding a
    hyperlink back to your site since both of our
    web sites are centered around the same niche. Would you prefer I link to you using your
    site address:
    http://www.blogger.com/comment.g?blogID=6927957479105321091&postID=2084624899354027593 or website title:
    Blogger: Zeeshan Umar's .Net Blog.
    Please make sure to let me know at your earliest convenience. Thanks

    Here is my homepage - View my web page
    my webpage - Go to my website

    ReplyDelete