Sunday, 11 August 2013

Call server side method client side in ASP.Net using jquery


jQuery allows you to call Server Side ASP.net methods from client side without any PostBack. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.

Client side methode

<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function fn_GetUserName() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetUserName",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>").val() + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>

Above the fn_GetUserName method makes an AJAX call which accepts the text box value  and returns a string value.
html code “cs.aspx”
<div>
Your Name :
<asp:TextBox ID="txtUsrNm" runat="server"></asp:TextBox>
<input id="btnClick" type="button" value="Show Current Time"
    onclick = "fn_GetUserName()" />
</div>

Server Side Methods
C#
[System.Web.Services.WebMethod]
public static string GetUserName(string name)
{
    return name;
}

No comments:

Post a Comment