Article of the Day, PageMethod - An Easier and Faster Approach for ASP.NET Ajax

On Sunday, Feb 20, 2011, my article 'PageMethod - An Easier and Faster Approach for ASP.NET Ajax' was selected as 'Article of the Day' at http://www.asp.net.


I also recommend to all of readers to do share useful articles on http://www.asp.net/community. Whenever you found an article which is interesting and can be useful for others.

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 !!