JQuery AJAX Example Code in Asp.net to Insert or Save Data into SQL Server Database without Postback in C#.Net VB.Net

In almost each and every web application we need to save or insert data into database. To save or insert data into database we need to postback into the server. Using AJAX we can provide the functionality without refreshing the browser. JQuery Ajax provides us an easier option to easily integrate Ajax functionality in ASP.Net web applications. In this article I will discuss “How to Save or Insert Data into SQL Server Databse using JQuery AJAX in ASP.Net C# and VB.Net Application“. By reading this article one can also learn how to integrate JQuery AJAX in ASP.Net applications.

Ultimate Output/Outcome:
JQuery AJAX Example Code in Asp.net to Insert Data into SQL Server Database in C# VB.Net

First Create the below SQL Server Table:

CREATE TABLE [dbo].[Articles](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](max) NULL,
	[Description] [varchar](max) NULL,
	[Author] [varchar](max) NULL,
	[Category] [varchar](50) NULL,

Prepare the aspx page HTML:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
        <tr><td>Artcile Title: </td><td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td></tr>
        <tr><td>Artcile Description: </td><td><asp:TextBox ID="txtDescription" runat="server"></asp:TextBox></td></tr>
        <tr><td>Author: </td><td><asp:TextBox ID="txtAuthor" runat="server"></asp:TextBox></td></tr>
        <tr><td>Category: </td><td>
            <asp:DropDownList ID="ddCategory" runat="server">
            <asp:ListItem Value="0" Text="Asp.Net"></asp:ListItem>
            <asp:ListItem Value="1" Text="C#.Net"></asp:ListItem>
            <asp:ListItem Value="2" Text="VB.Net"></asp:ListItem>
            <asp:ListItem Value="3" Text="JQuery Ajax"></asp:ListItem>
        <tr><td colspan="2"><div id="divStatus"></div></td></tr>
        <tr><td><asp:Button ID="cmdSave" runat="server" Text="Save"/></td><td></td></tr>

Note: Don’t forget to add ScriptManager with EnablePageMethods=”true” in your page.

Modify Web.config file to connect with Database:

    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Save or Insert Data from Code Behind using WebMethod:
C# Code:

    public static string Save_Data(string sName, string sDescription,string sAuthor,string sCategory)
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
                using (SqlCommand cmd = new SqlCommand("Sp_SaveArticle", con))
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Name", sName);
                    cmd.Parameters.AddWithValue("@Description", sDescription);
                    cmd.Parameters.AddWithValue("@Author", sAuthor);
                    cmd.Parameters.AddWithValue("@Category", sCategory);
                    Int32 retVal = cmd.ExecuteNonQuery();
        catch (Exception Ex)
            return "ERROR: Unable to save data !!</br>"+Ex.Message;

        return "Data Saved Successfully!";

Note: Don’t forget to add “System.Data.SqlClient”, “System.Configuration” and “System.Data” namespaces.

VB.Net Code:

    <System.Web.Services.WebMethod()> _
    Public Shared Function Save_Data(sName As String, sDescription As String, sAuthor As String, sCategory As String) As String
            Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
                Using cmd As New SqlCommand("Sp_SaveArticle", con)
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.Parameters.AddWithValue("@Name", sName)
                    cmd.Parameters.AddWithValue("@Description", sDescription)
                    cmd.Parameters.AddWithValue("@Author", sAuthor)
                    cmd.Parameters.AddWithValue("@Category", sCategory)
                    Dim retVal As Int32 = cmd.ExecuteNonQuery()
                End Using
            End Using
        Catch Ex As Exception
            Return "ERROR: Unable to save data !!</br>" + Ex.Message
        End Try

        Return "Data Saved Successfully!"
    End Function

Note: Don’t forget to add “System.Data.SqlClient”, “System.Configuration” and “System.Data” namespaces.

Add JQuery AJAX script into your Page:

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=cmdSave.ClientID %>').click(function () {

                var Name = $.trim($('#<%=txtName.ClientID %>').val());
                var Description = $.trim($('#<%=txtDescription.ClientID %>').val());
                var Author = $.trim($('#<%=txtAuthor.ClientID %>').val());
                var Category = $('#<%=ddCategory.ClientID %>').val();
                //For more on DropDownList
                //Visit http://codedisplay.com/jquery-to-get-selectedvalue-selectedindex-selectedtext-of-a-dropdownlist-asp-net-c-vb-net/

                    type: "POST",
                    url: "Default.aspx/Save_Data",
                    data: "{'sName':'" + Name + "', 'sDescription':'" + Description + "','sAuthor':'" + Author + "','sCategory':'" + Category + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (Response_msg) {
                        if (Response_msg.d.indexOf("ERROR") < 0) {
                            $('#divStatus').css({ "font-weight": "bold", "color": "Green" })
                            $('#<%=txtName.ClientID %>').val("")
                            $('#<%=txtDescription.ClientID %>').val("")
                            $('#<%=txtAuthor.ClientID %>').val("")
                            $('#<%=ddCategory.ClientID %>').val("0")
                        else {
                            $('#divStatus').css({ "font-weight": "bold", "color": "Red" })
                    error: function (xhr, status, errorThrown) {
                        $('#divStatus').html(errorThrown + '</br>' + status + '</br>' + xhr.statusText)
                return false;

Now run the application. Hope you can save or insert data from your Asp.Net C# or VB.Net application into SQL Server Database. If any issue please download code example from below.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Ajax, Asp.net, C#, Client, Database, JQuery, SQL Server, VB.Net
4 comments on “JQuery AJAX Example Code in Asp.net to Insert or Save Data into SQL Server Database without Postback in C#.Net VB.Net
  1. Yohan says:

    Please Help Me…!!! ERROR: Unable to save data !! Could not find stored procedure ‘Sp_SaveArticle’.

  2. sirazdb says:

    Happy coding. very easy tut.

  3. Mohammad says:

    what is “Sp_savearticle” is it table name? or function or just an string ???? I just confused with this part..

    • Shawpnendu Bikash says:

      Sorry Readers, Sp_savearticle is a stored procedure which is used to insert data through ajax web method call. Please find the script from below:

      CREATE PROCEDURE [dbo].[Sp_SaveArticle] @Name VARCHAR(MAX), @Description VARCHAR(MAX), @Author VARCHAR(MAX), @Category VARCHAR(50) AS BEGIN INSERT INTO Articles (Name,Description,Author,Category) VALUES (@Name,@Description,@Author,@Category) END GO

Leave a Reply

Your email address will not be published. Required fields are marked *