Web Method call in ASP .NET using JQuery AJAX
In ASP .NET WebMethod is Attribute used for the method to be treated as Web Service. The method attached with WebMethod attribute is public which becomes part of XML web services. There is lot to talk about WebMethod, it's properties That I will cover in another blog coming soon. Here I will show you how can you call WebMethod using JQuery. Let's consider the simple example of Concatenation of two words,say your first name and last name. Here I will send this 2 words from two textbox's to the WebMethod which will return the concatenated string. The Method attached with WebMethod attribute is concatenate Now to send txtFirstName & txtLastName to method concatenate.We must send it in JSON format,server side function accepts data in JSON format only from client side.There are multiple approaches to do this,but I use JSON.stringify() function.And the Server side method responses with JSON data. This article is only about Calling WebMethod using JQuery,AJAX.To understand How to access WebControls in JQuery read the article Use of JavaScript in ASP .NET over AutoPostBack.
This is just simple example to demonstrate WebMethod call using JQuery & AJAX.It's not recommended to use server side code for these type of simple operations.If you have any queries and/or suggestions,Please comment below.
<asp:TextBox id="txtFirstName" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btn" runat="server" Text="Send To WebMethod" />
<br />
<asp:TextBox ID="txtResult" runat="server"></asp:TextBox>
[System.Web.Services.WebMethod]
public static string concatenate(string firstName, string lastName)
{
return firstName + " " + lastName;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$("#<%= btn.ClientID %>").on("click", function (e) {
e.preventDefault();
var firstName = $("#<%= txtFirstName.ClientID %>").val();
var lastName = $("#<%= txtLastName.ClientID%>").val();
var data = { firstName: firstName, lastName: lastName };
var JSONdata = JSON.stringify(data);
$.ajax({
url: "WebMethod.aspx/concatenate",
data: JSONdata,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(result)
{
$("#<%= txtResult.ClientID %>").val(result.d);
}
});
});
</script>
This is just simple example to demonstrate WebMethod call using JQuery & AJAX.It's not recommended to use server side code for these type of simple operations.If you have any queries and/or suggestions,Please comment below.
Comments
Post a Comment