This article is all about calling an Ajax request to an ASP.NET based website. Most efficient and easiest way to implement Ajax request-response flow in ASP.NET is using Web-Method. Basically, as in general if we require to call ajax in .NET then either we create a new webpage for serving that request separately or we create a Web-Service for the same.
Lets get-rid-of these solutions because we do have a better one in place. Actually suggested solution is mixture of both with more flexibility and stability:-
This implementation has following easy steps to implement. Lets consider the same with an example:
- Create a ASP.NET Website.
- Add a webpage say “Default.aspx” and set as start-up page.
- Include jQuery reference in you aspx page.
<script src="Scripts/jquery-1.9.0.js" type="text/javascript"></script>
-
In your code behind file of Default.aspx i.e. Default.aspx.cs, include a NameSpace as follows:
using System.Web.Services;
-
In your code behind file of Default.aspx i.e. Default.aspx.cs, Create a WebMethod as a public Static. It should be static so that easily can be called with URL publicly like http://localhost/default.aspx/testajax :
[WebMethod()] public static string testajax(int testParam) { /*You can do database operations here if required*/ return "testParam is" + testParam.ToString(); }
That’s all for code behind.
-
Now prepare you frontend to send and receive ajax using script:
function syncToServerViaAjax(param) { jQuery.ajax({ url: 'Default.aspx/testajax', type: "POST", data: "{'testParam':" + param+ "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert(data.d); } }); }
-
now you can call this function on any specific event and to process data. As:
Add a button into HTML:
<button onclick="syncToServerViaAjax(2)">Click</button>
That’s All about handling Ajax in ASP.NET. Do let me know your thoughts as well queries on the same. Thanks.
0 Comments.