Wednesday, November 24, 2010

Calling server side code from client side

Today, I am going to explain you how to call a server side function/code from client side (JavaScript).

Ajax provide us the facility to use server side code from client side without postback.

You can call server side code by using webservice(.asmx) or using page methods in same aspx page.
The page methods are rendered as inline javascript.

If you are using asp.net 2.0 then you require
ASP.NET AJAX extensions for ASP.NET 2.0

you website need to be ajax enabled for using this functionality.

I just explaining this functionality by a simple Example

add a javascript file naming script.js in you website

and write below methos in your javascript file

function CallMe(src,dest)
 {   
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetGroupName(ctrl.value, CallSuccess, CallFailed, dest);
 }

 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {   
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }

 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }



now move on to your aspx page
add  a reference of your javascript file in body tag of page


and paste below code 


<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
    <div>
        <asp:Label ID="lbl_Group_Code" runat="server" Text="Group Code"></asp:Label>
        <asp:TextBox ID="txt_Group_Code" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txt_Group_Name" runat="server" ReadOnly="True"></asp:TextBox><br />
    </div>
    </form>





also remember to check following property of script manager in script manager tag
 EnablePageMethods="true" 
this property enables your code to use server side webmethods


now come to your aspx.cs page


write a public static method here as follows


   public static string GetGroupName(string GRP_CODE)
        {
            if (GRP_CODE == null || GRP_CODE.Length == 0)
                return String.Empty;
            OracleConnection conn = null;
            try
            {
                string connection = ConfigurationManager.ConnectionStrings["csTextile"].ConnectionString;
                conn = new OracleConnection(connection);
                string Oracle = "Select GRP_NAME from FA_GRP_MST where GRP_CODE = :GRP_CODE";
                OracleCommand cmd = new OracleCommand(Oracle, conn);
                cmd.Parameters.Add(":GRP_CODE", OracleType.VarChar).Value = GRP_CODE;
                conn.Open();
                string GRP_Name = Convert.ToString(cmd.ExecuteScalar());
                return GRP_Name;
            }
            catch (OracleException ex)
            {
                return "error";
            }
            finally
            {
                conn.Close();
            }
        }





Method should be public static


I use Oracle as database in my website so I use OracleConnection and Command etc...
replace Oracle with sql in your app.


now add following line before your method


   [System.Web.Services.WebMethod]


like this


   [System.Web.Services.WebMethod]
        public static string GetGroupName(string GRP_CODE)
        {
            if (GRP_CODE == null || GRP_CODE.Length == 0)
                return String.Empty;
            OracleConnection conn = null;
            try
            {
                string connection = ConfigurationManager.ConnectionStrings["csTextile"].ConnectionString;
                conn = new OracleConnection(connection);
                string Oracle = "Select GRP_NAME from FA_GRP_MST where GRP_CODE = :GRP_CODE";
                OracleCommand cmd = new OracleCommand(Oracle, conn);
                cmd.Parameters.Add(":GRP_CODE", OracleType.VarChar).Value = GRP_CODE;
                conn.Open();
                string GRP_Name = Convert.ToString(cmd.ExecuteScalar());
                return GRP_Name;
            }
            catch (OracleException ex)
            {
                return "error";
            }
            finally
            {
                conn.Close();
            }
        }




now add the following code in page load event


if (!Page.IsPostBack)
            {
                txt_Group_Code.Attributes.Add("onblur", "javascript:CallMe('" + txt_Group_Code.ClientID + "', '" + txt_Group_Name.ClientID + "')");
                txt_Group_Code.Attributes.Add("onchange", "javascript:CallMe('" + txt_Group_Code.ClientID + "', '" + txt_Group_Name.ClientID + "')");
            }

now test your code

write if any problem occurs

have a happy coding

No comments:

Post a Comment