Calling ASP.Net WebMethod using jQuery AJAX

What is WebMethod?

Web methods are those methods which are generally exposed over the web for eg - in a Web service. A web method must contain an attribute [WebMethod].  A web method can be called from server side code as well as client side code. In this blog, I will write about how to call a WebMethod using Jquery AJAX.

Jquery allow users to call server side code without any postback.
Follow below steps:

Create a table with below script:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_PADDING ON

GO

CREATE TABLE [dbo].[userTable](

[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL
) ON [PRIMARY]

GO


SET ANSI_PADDING OFF

GO


Write a stored procedure to save data into the table:


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE InsertData

@name varchar (50)
AS
BEGIN

SET NOCOUNT ON;
insert into [dbo].[userTable] (name) values(@name)
END
GO

AJAX Method to Call Web method


function SaveData() {       
var name = document.getElementById('<%=txtName.ClientID %>').value;             
$.ajax({         
type: "POST"
url: /MyFolder/MyAjaxPage.aspx / SubmitData ",         
data: '{"name":"' + name + '"}'
contentType: "application/json; charset=utf-8"
dataType: "json"
success: function(data) {           
             if (data.d == "success") {            
alert('Your data has been submitted.');
           
}
                   
}, 
error: function() {           
alert('Please Try again.');
           
return false;
         
}       
});
     


Web method

Declare below connection string within the class.

SqlConnection sqlConnection = new SqlConnection("database connection string");
    [WebMethod]
    public static string SubmitData(string name)
    {
        try
        {
            SqlParameter[] prmUserReg = new SqlParameter[1];
            prmUserReg[0] = new SqlParameter("@name", name);
            SqlCommand cmd = new SqlCommand("InsertData", sqlConnection);
            cmd.CommandType = CommandType.StoredProcedure;
            if (sqlConnection.State == ConnectionState.Closed)
            {
                sqlConnection.Open();
            }
            cmd.Parameters.AddRange(prmUserReg);
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
        }

        finally
        {
        }

        return message;
    } 

Comments

Popular

SharePoint Interview Questions and Answers

What is Cloud Computing - A guide for beginners