In this article I will explain with an example, how to submit form to database without page refresh using jQuery AJAX and JSON in ASP.Net.
This article will also explain how use an ASP.Net WebMethod to fetch data from the form fields i.e. TextBox, DropDownList, etc. and later insert it into database table.
Database
I have made use of the following table named Users with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The following HTML Markup consists of two TextBoxes, a Button control and a GridView control.
The GridView control will be used to display the inserted Usernames and Passwords.
The Button has been assigned jQuery Click event handler.
<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">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Username"/>
<asp:BoundField DataField="Password" HeaderText="Password"/>
</Columns>
</asp:GridView>
Class Implementation
The following class consists of two properties i.e. Username and Password.
Note: An object of this class will be used to fetch and hold and transfer the Username and Password values between the Client and the Server.
C#
public class User
{
public string Username { get; set; }
public string Password { get; set; }
}
VB.Net
Public Class User
Public Property Username() As String
Public Property 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;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
Binding the GridView
Inside the Page Load event, 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 (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Users", con))
{
DataTable dt = new DataTable();
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 sda As New SqlDataAdapter("SELECT * FROM Users", con)
Dim dt As New DataTable()
sda.Fill(dt)
gvUsers.DataSource = dt
gvUsers.DataBind()
End Using
End Using
End If
End Sub
Server Side WebMethod
The following WebMethod will be called using jQuery AJAX function on the Client Side.
The User object sent from the Client Side is accepted as parameters and then the values of the Username and Password are inserted into the SQL Server Database table.
C#
[WebMethod]
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()> _
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
jQuery AJAX implementation
When the Save Button is clicked, the values of the Username and Password TextBoxes are wrapped into a JSON object.
Then the JSON object is passed to the Server Side WebMethod using the jQuery AJAX call.
Note: The names of the properties within the class must exactly match with that of the JSON object otherwise the jQuery AJAX will NOT call the WebMethod.
Finally, inside the Success event handler, a JavaScript Alert Message Box is displayed and the page is reloaded in order to refresh the GridView.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://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>
Screenshot
Downloads