In this article I will explain how to insert or update data asynchronously (without PostBack) to database using jQuery AJAX and Page Methods (WebMethod on Page) in ASP.Net.
 
Database Schema
I have created a new database named UsersDB which consist of one table named Users with the following schema.
Save Form Data to Database with jQuery AJAX in ASP.Net
 
HTML Markup
The HTML Markup consists of Username and Password TextBoxes and a GridView to display the inserted Usernames and Passwords via jQuery AJAX.
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>
            Username:
        </td>
        <td>
            <asp:TextBox ID="txtUsername" runat="server" Text="" />
        </td>
    </tr>
    <tr>
        <td>
            Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button ID="btnSave" Text="Save" runat="server" />
        </td>
    </tr>
</table>
<hr />
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2"
    HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2">
    <Columns>
        <asp:BoundField DataField="Username" HeaderText="Username" />
        <asp:BoundField DataField="Password" HeaderText="Password" />
    </Columns>
</asp:GridView>
 
 
jQuery AJAX Implementation to save Form data to database in ASP.Net
Below is the jQuery AJAX implementation to save the form data i.e. value of the Username and Password TextBoxes to database.
Note: If you want to know more about the jQuery AJAX usage in ASP.Net, please refer Call ASP.Net Page Method using jQuery AJAX
A JavaScript Custom Object with the name user is created and the within it I have added two child properties Username and Password, this resemble a class object in C#.
The Username and Password TextBox values are set within these properties and then the Object converted to a string using the JSON stringify method of the JSON2.js library and it is passed as data parameter to the jQuery AJAX Method call to the SaveUser method.
When the jQuery AJAX Call is successful a JavaScript Alert message is displayed and the page is reloaded so that the record can be viewed within the GridView control.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=btnSave]").bind("click", function () {
            var user = {};
            user.Username = $("[id*=txtUsername]").val();
            user.Password = $("[id*=txtPassword]").val();
            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveUser",
                data: '{user: ' + JSON.stringify(user) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("User has been added successfully.");
                    window.location.reload();
                }
            });
            return false;
        });
    });
</script>
 
 
Class Implementation
Below is the class implementation, this class resembles the JavaScript Custom Object (discussed earlier). This object will be used to fetch and hold the Username and Password values sent by the jQuery AJAX method.
Note: It is very important the names of the Properties within the class must exactly match with that of the JavaScript Custom object Properties otherwise the jQuery AJAX will not execute the WebMethod.
C#
public class User
{
    public string Username { get; set; }
    public string Password { get; set; }
}
 
VB.Net
Public Class User
    Public Property Username() As String
        Get
            Return _Username
        End Get
        Set(value As String)
            _Username = Value
        End Set
    End Property
    Private _Username As String
    Public Property Password() As String
        Get
            Return _Password
        End Get
        Set(value As String)
            _Password = Value
        End Set
    End Property
    Private _Password As String
End Class
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Services;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Imports System.Web.Script.Services
 
 
Server Side WebMethod to handle the jQuery AJAX Call
The following WebMethod will be executed when the jQuery AJAX call is made from client side. This method accepts the User object from client side and then the Username and Password values are inserted in the database.
C#
[WebMethod]
[ScriptMethod]
public static void SaveUser(User user)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)"))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Username", user.Username);
            cmd.Parameters.AddWithValue("@Password", user.Password);
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}
 
VB.Net
<WebMethod ()> _
<ScriptMethod ()> _
Public Shared Sub SaveUser(user As User)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand("INSERT INTO Users VALUES(@Username, @Password)")
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@Username", user.Username)
            cmd.Parameters.AddWithValue("@Password", user.Password)
            cmd.Connection = con
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
End Sub
 
 
Adding ASP.Net GridView control to display the inserted records
In the Page Load event handler of the Page, the ASP.Net GridView is populated with the records from the Users table.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    DataTable dt = new DataTable();
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                    gvUsers.DataSource = dt;
                    gvUsers.DataBind();
                }
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("SELECT * FROM Users")
                Using sda As New SqlDataAdapter()
                    Dim dt As New DataTable()
                    cmd.CommandType = CommandType.Text
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    sda.Fill(dt)
                    gvUsers.DataSource = dt
                    gvUsers.DataBind()
                End Using
            End Using
        End Using
    End If
End Sub
 
Save Form Data to Database with jQuery AJAX in ASP.Net
 
Downloads