Pages

Tuesday, December 7, 2010

Calling Server side function using javascript

Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.

Default.aspx
<script type='text/javascript'>
       function DisplayMessage() {
            PageMethods.Message("Amit",OnGetMessageSuccess, OnGetMessageFailure);
        }
        function OnGetMessageSuccess(result, userContext, methodName) {
            alert(result);
        }
        function OnGetMessageFailure(error, userContext, methodName) {
            alert(error.get_message());
        }

function CallMe(src, dest) {
            var ctrl = document.getElementById(src);
            // call server side method
            PageMethods.GetContactName(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());
        }
    </script>
<body>
    <form id='form1' runat='server'>
    <asp:ScriptManager ID='ScriptManager1' runat='server'  EnablePageMethods='true' />
<div>
            <input type='submit' value='Get Message' onclick='DisplayMessage();return false;' 

/>
<asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
        <asp:TextBox
            ID="txtId1" runat="server"></asp:TextBox>
        <br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />

</div>
</form>
</body>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
                    }
    }
[System.Web.Services.WebMethod]
    public static string Message(string str)
    {
        return str;
    }

[System.Web.Services.WebMethod]
    public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationSettings.AppSettings["ConnectionString"];
            conn = new SqlConnection(connection);
            string sql = "Select sEmpFName from EMP_EmpPersonal where iEmployeeId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            if (contNm.Length > 0)
                return contNm;
            else
                return "No record found.";
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }

No comments:

Post a Comment