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

How to end session when browser is closed

In high traffic sites sessions are very costly and they use lots of server's memory. Generally session timeout is 20 min (by default) and even if user closes the browser. Values in session still exist until session get expired after timeout. We can save lots of server memory if we destroy session as user closes the browser.

Here is how you can do it:-

1)First create a page AutoLogOut.aspx and in Page_Load event write this code:-
protected void Page_Load(object sender, EventArgs e)
{
    Session.Abandon();
}

2- Then add following javascript code in your page or Master Page:-
<script type="text/javascript">
     var clicked = false;
    function CheckBrowser()
    {
        if (clicked == false)
        {
            //Browser closed
        }
        else
        {
            //redirected 
            clicked = false;
        }
    }
 
    function bodyUnload()
    {
        if (clicked == false)//browser is closed
        {
            var request = GetRequest();
            
            request.open("GET""AutoLogOut.aspx"true);
            request.send();
        }
    }
 
    function GetRequest()
    {
        var request = null;
        if (window.XMLHttpRequest)
        {
            //incase of IE7,FF, Opera and Safari browser
            request = new XMLHttpRequest();
        }
        else
        {
            //for old browser like IE 6.x and IE 5.x
            request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }
        return request;
    } 

3- Finally on your body tag add these event handlers:-
<body onunload="bodyUnload();" onclick ="clicked=true;>

Now when user closes the browser, it will close session on server. However I just like to highlight that this solution might not work 100% time as there are chances that when user close the browser, he is not connected to internet.

Feel free to share your comments on my post.

Real World Scenario: Object Writer

Recently in a project I was facing a bug which was very difficult to reproduce. So, I decided to log object with complete properties in a text file. This code can be really useful for those who want to solve bugs which only occurs very rarely.

Here is the code of my class which converts object into a string:-

public class ObjectWriter
{
    public static string GetObjectString(object obj)
    {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("Type: ");
        sb.AppendLine(obj.GetType().ToString());
 
        if (obj == null)
        {
            sb.AppendLine("Value: Null");
        }
        else
        {
            sb.AppendLine("-------------------------");
            var type = obj.GetType();
 
            foreach (var prop in type.GetProperties())
            {
                var val = prop.GetValue(obj, new object[] { });
                var valStr = val == null ? "" : val.ToString();
                sb.AppendLine(prop.Name + ":" + valStr);
            }
        }
        return sb.ToString();
    }
}


Here is sample output and usage of my code:-


In above image I have called ObjectWriter.GetObjectString(ie) and in result varibale you can see that I can see its type and other fields information. You can write this information in log file for further investigation.

How to keep session alive in ASP.Net using Webservice and jQuery

Most of the time when we develop intranet web applications, our clients request us that they only have to log in in the morning when they reach office. It seems very easy to implement i.e. increase session timeout to 10+ hours and we are done.

But there is a drawback of this approach. Even if user close the browser, session's data will occupy server's memory till 10+ hours and our site's performance will go down. So, this is certainly not a good choice for us.

There are many alternates to solve above problem. In this post, I am sharing one of the possible solution.

First I have created an asmx service i.e. SessionAlive:-

/// <summary>
    /// Summary description for SessionAlive
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class SessionAlive : System.Web.Services.WebService
    {
 
        [WebMethod]
        public void UpdateSession()
        {
            HttpContext.Current.Session["tempVariable"] = DateTime.Now;
        }
    }

Note that by default [System.Web.Script.Services.ScriptService] is commented when you create a new service. You need to uncomment above line to ensure that methods in this service are accessible for javascript or jQuery.

Also i have created UpdateSession() method which updates a value in session.

Now here is the javascript which I added in my page.

<script type="text/javascript" src="JS/jquery-1.4.2.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        setTimeout(updateSession, 1000*60);//Timeout is 1 min
    });
    
    function updateSession() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "SessionAlive.asmx/UpdateSession",
            data: "{}",
            dataType: "json"
        });
        setTimeout(updateSession, 1000 * 60);
    }
</script>

Above function calls web service after every minute to ensure that session is not time out. Hopefully this will be useful for you. Feel free to add comments and suggestions.

PageMethod an easier and faster approach for Asp.Net AJAX

We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:-

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

Here is how my Page looks like:-


To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true. This will tell ScriptManager that I am going to call Page Methods from client side.

Now Next step is to Create a Server Side function. Here is the function which I created, this function validates user's input:-


[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
 
    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password canonot be less than 5 chars";
    }
 
    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things. First this method should be 'public static'. Second there should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:-

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods. My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>


Finally I have pressed Signup button and I am geting these messages.

See it is really simple. Now there is a fair chance that instead of these fancy looking messages you might be getting this error:-

If you see error like this then double check following things:-
  1. You have set EnablePageMethods="true" in ScriptManager.
  2. You have added [WebMethod] tag in your server side method.
  3. Your server side method is 'public static'

Hopefully this will be useful for you feel free to share your comments and suggestions.