Wednesday, October 12, 2016

How to call WebMethod from JQuery



Script


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetCurrentTime",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>


WebMothod

in C# or VB

C#

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

VB

<System.Web.Services.WebMethod()> _
Public Shared Function GetCurrentTime(ByVal name As StringAs String
   Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
            DateTime.Now.ToString()
End Function

No comments:

Post a Comment