How to call Asp.Net page method using jQuery Ajax call?
In this tutorial,I am going to explain "How to call Asp.Net page method using jQuery Ajax call?". Before moving further let's understand the JQuery ajax call.
Basically javascript/JQuery library provides a way to call webmethod ,webservices and Web API's asynchronously.It means there will be no postback while calling method through ajax call.We can also say that it is an alternative of update panel.
Below is the basic syntax of JQuery ajax call.
Step 1: Open visual studio and create a Default.aspx page and write below markup under it.
1 2 3 4 5 6 7 8 9 | <div> First Name : <asp:TextBox ID= "txtFirstName" runat= "server" ></asp:TextBox> Last Name : <asp:TextBox ID= "txtLastName" runat= "server" ></asp:TextBox> <input id= "btnGetFullName" type= "button" value= "Generate Full Name" onclick = "GetFullName()" /> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <span class= "line-number" ><span><a>1</a></span><span><a>2</a></span><span><a>3</a></span><span><a>4</a></span><span><a>5</a></span><span><a>6</a></span><span><a>7</a></span><span><a>8</a></span><span><a>9</a></span><span><a>10</a></span><span><a>11</a></span><span><a>12</a></span><span><a>13</a></span><span><a>14</a></span><span><a>15</a></span><span><a>16</a></span><span><a>17</a></span><span><a>18</a></span><span><a>19</a></span><span><a>20</a></span><span><a>21</a></span></span> <script src= "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type= "text/javascript" ></script> <script type= "text/javascript" > function GetFullName() { $.ajax({ type: "POST" , url: "CS.aspx/GetMyFullName" , data: "{ firstname: '" + $( "#<%=txtFirstName.ClientID%>" ).val() + "',lastname: '" + $( "#<%=txtLastName.ClientID%>" ).val() + "'}" , contentType: "application/json; charset=utf-8" , dataType: "json" , success: ShowMyName, failure: function (response) { alert(response.d); } }); } function ShowMyName(response) { alert(response.d); } </script> <span class= "cl" ></span> |
Now create a webmethod in Default.aspx.cs.(Make sure webmethod are always static)
1 2 3 4 5 | [System.Web.Services.WebMethod] public static string GetMyFullName( string firstname, string lastname) { return firstname + " " + lastname; } |
This is a simple ajax call to webmethod to get fullname of user.
Hope you liked this tutorial.Please provide your feedback.
Thanks.
How to call Asp.Net page method using jQuery Ajax call?
Reviewed by CodiBucket
on
07:40
Rating:

No comments: