How to Call Code Behind Method using jQuery AJAX in ASP.NET

Leave a Comment

In this article, we have to learn how to call a code behind method using jQuery AJAX in ASP.NET Website.

To call a Code web page method add New Web Form Default.aspx page.

Now in Default.aspx code behind page Default.aspx.cs page, add below namespace to enable page method.
using System.Web.Services; 

Now add below code to your default.aspx.cs page Page_Load event-
public static string[] UserNameArray;
protected void Page_Load(object sender, EventArgs e)
{
  UserNameArray = new string[7] { "testid01", "testid02", "testid03", "testid04", "testid05", "testid06", "testid07" };
}
[WebMethod()]
public static bool CheckUserName(string sUserName)
{
foreach (string strUsername in UserNameArray){
if (sUserName == strUsername)
return true;
}
return false;
}

In above code, we will create one array called UserNameArray and also crate one page method.

Now add below coed to your Default.aspx Page
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        <asp:Button ID="btnSubmit" runat="server" Text="Check User Name" />
    </div>
    </form>

Now to call a Page Method on Button (Contain id name btnSubmit) using jQuery AJAX, add below script -
<script src="jquery-1.8.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#btnSubmit").click(function (e) {
            e.preventDefault();
            if ($("#txtUserName").val() == '')
                alert("Please enter the UserName");
            else
                sendData($("#txtUserName").val());
        });
        function sendData(sUserName) {
            var loc = window.location.href;
            loc = (loc.substr(loc.length - 1, 1) == "/") ? loc +
"Recipe3.aspx" : loc;
            $.ajax({
                type: "POST",
                url: loc + "/CheckUserName",
                data: '{"sUserName":"' + sUserName + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if (msg.d)
                        alert("The User Name is valid");
                    else
                        alert("The User Name is invalid")
                },
                error: function () {
                    alert("An unexpected error has occurred during processing.");
                }
            });
        }
    });
</script>
In above code CheckUserName is a page method. we can set this method as shown below in above script.
url: loc + "/CheckUserName",

Demo
Call Code Behind Method using jQuery AJAX in ASP.NET
In this demo We can check if the user name entered by the end user is valid.

Download Source Code

0 comments:

Post a Comment