Friday 23 October 2015

how to call ajax with Jquery using Asp.net

how to call ajax with Jquery using Asp.net
Hello friends here i am show you a example how to ajax call using asp.net server side code:


Many of the times the interviewer asked the question that how to call how to call server side method as a client side in Asp.net.

so the answer is using jquery we can use server side method via client side:
here is example for this.


first of all create a sample web application in visual studio

1. visual studio 2012->new project - web application .


now on default.aspx page write the following code in body tag.


<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        <input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />


after that call the jquery within head section like this ..


<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: "WebForm1.aspx/GetCurrentTime",
                data: '{name:"' + $("#<%=txtUserName.ClientID%>")[0].value + '"}',
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (responce) {
                    alert(responce.d);
                }
            });
        }
        function OnSuccess(responce) {
            alert(responce.d);
        }
    </script>

you can see easily the above code
in the first line we reference the jquery file user can also download this jquery and reference it to locally.

now in function ShowCurrentTime() we make ajax call here $.ajax is signature for call ajax method

here type may be post or get according to user requirement.

now it is main part on default.aspx.cs page make method to as webmethod which is necessary to call server method on client side

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


You can test this demo and enjoy..

No comments:

Post a Comment

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow