Tuesday, August 10, 2010

Calling Server Side Function from javascript


Hello developers,


Many times what happens is that we are using HTML controls in an aspx page and we want to have database interaction to populate some control,
or when we are not willing to use complex javascript functions for string manipulation or any other stuff,
Then we just eagerly want to use the server side functions or database connectivity without postback.


Best thing that you can do that time is write the entire code in Server side function and then call that function from  client side javascript.


In this blog, I am going to tell you exactly this thing:



At codebehind file, create your server side method and write following two lines before that:
[System.Web.Services.WebMethod]
 [System.Web.Script.Services.ScriptMethod()]
This will make your server side function visible to javascript.

Note: Do remember to set EnablePageMethods property od ScriptManager to true.


A simple Example:

At codebehind file:
[System.Web.Services.WebMethod]
 [System.Web.Script.Services.ScriptMethod()]
    public static string SayHello()
    {
string strData = “Hello”;      
return strData;
    }

From Javascript: Call your server side method from your javascript nethod by using 
PageMethods. OnSucceeded and OnFailed are two callback functions which are always passed as parameters.

function  AlertingHello(){
PageMethods.SayHello(OnSucceeded, OnFailed);

}

 If your server side method will execute successfully, you will get the result in the OnSucceeded function:
function OnSucceeded(result, userContext, methodName) {
if(methodname==”SayHello”)
{
 alert(result);//you will get "Hello" in result.
}
}



If your server side method will not execute successfully, you will get the result in the OnFailed function. You can write nay code in the onFailed method to tell the user that the error occurred.




function OnFailed(error, userContext, methodName) {
if(methodname==”SayHello”)
{
 alert("Some Error Occurred");
}
}


A complex Example:

Imagine there are are few textfields that you want to fill on the selection of a dropdown or select control of html:

Here the scenario is We'll select the name of an employee from a dropdown list and 
and accordingly Fill his details in textfields.

At OnChange event of dropdown, you can call the javascript function:

In Client side page:

  function FillDataInControls() {
                var dropDown = document.getElementById('<%=ddlName.ClientID%>');
                var name = dropDown.options[dropDown.selectedIndex].value;
                PageMethods.FillControls(name, OnSucceeded, OnFailed);
            }

At code behind file:

[System.Web.Services.WebMethod]
 [System.Web.Script.Services.ScriptMethod()]


    public static string FillControls(string name)
    {
        DataSet dsDetails = new DataSet();
        string strData = string.Empty;
        try
        {
            if (name != "")
            {
                GetDetailsBL objGetDetailsBL = new GetDetailsBL();
                dsDetails = objAddCoupanBL.GetddlCouponCode(name);

                if (dsDetails.Tables[0].Rows.Count > 0)
                {
                    strData = name;
                    employeeId = int.Parse(dsDetails.Tables[0].Rows[0]["EmployeeId "].ToString());
                    dob = dsDetails.Tables[0].Rows[0]["dob"].ToString();
                    strData = strData + "^" + dob;
                    address= dsDetails.Tables[0].Rows[0]["address"].ToString();
                    strData = strData + "^" + address;
                    dateofjoin= dsDetails.Tables[0].Rows[0]["dateofjoining"].ToString();
                    strData = strData + "^" + dateofjoin;
                    position= dsDetails.Tables[0].Rows[0]["position"].ToString();
                    strData = strData + "^" + position;
                    manager= dsDetails.Tables[0].Rows[0]["managerId"].ToString();
                    strData = strData + "^" + manager;
                    salary= dsDetails.Tables[0].Rows[0]["salary"].ToString();
                    strData = strData + "^" + salary;
                }
            }
        }
        catch { }
        return strData;
    }

In Client side page:

create the callback function onSucceeded like this: I am assuming that all the text fields are html controls.
If the text fields are server side controls:
we can use 
document.getElementById('<%=txtEmpName.ClientID%>').value
instead of
document.getElementById('txtEmpName').value

function OnSucceeded(result, userContext, methodName) {
if (methodName == "FillControls") {
   if(result!="")
   {
    var data = result.split('^');
document.getElementById('txtEmpName').value=data[0];
document.getElementById('txtEmpId').value=data[1];
document.getElementById('txtEmpDob').value=data[2];
document.getElementById('txtEmpAddress').value=data[3];
document.getElementById('txtEmpDateOfJoin').value=data[4];
document.getElementById('txtEmpPosition').value=data[5];
document.getElementById('txtEmpManager').value=data[6];
document.getElementById('txtEmpSalary').value=data[7];
     }


  }
}

That's it about "Calling Server Side Function from Javascript". 
I hope it helps.
:)











No comments:

Post a Comment