Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Insert Data into Database using jQuery Ajax Method in Asp.net using C#, VB.NET

May 3, 2015
Introduction

Here I will explain how to insert data into database using
jQuery ajax method in asp.net using c#, vb.net or jQuery insert data into database without postback in in asp.net using c#, vb.net.


Before implement this example first design one table sampleinfo in your database like as shown below

Column Name
Data Type
Allow Nulls
subjectid
Int(IDENTITY=TRUE)
Yes
Name
varchar(50)
Yes
subject
varchar(50)
Yes
Description
varchar(250)
Yes
Once we design table in our database that would be like as shown below


Now open your aspx page and write the code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
<title>Insert data into database using jquery in asp.net</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="txtname" /></td>
</tr>
<tr>
<td>Subject:</td>
<td> <input type="text" id="txtsubject" /></td>
</tr>
<tr>
<td>Body:</td>
<td> <textarea id="txtbody"></textarea></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
<label id="lblmsg"/><br />
<asp:GridView ID="gvDetails" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</form>
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#txtname').val();
var subject = $('#txtsubject').val();
var body = $('#txtbody').val();
if (name != '' && subject != '' && body) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "InsertDataintoDatabase.aspx/InsertData",
data: "{'username':'" + name + "','subj':'" + subject + "','desc':'" + body + "'}",
dataType: "json",
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#txtname').val('');
$('#txtsubject').val('');
$('#txtbody').val('');
$('#lblmsg').html("Details Submitted Successfully");
window.location.reload();
}
},
error: function (result) {
alert("Error");
}
});
}
else {
alert('Please enter all the fields')
return false;
}
})
});
</script>
</body>
</html>

Now add following namespaces in code behind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

After completion of adding namespaces you need to write the code like as shown below


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGridviewData();
}
protected void BindGridviewData()
{
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd = new SqlCommand("select * from sampleinfo", con))
{
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
}
}
[WebMethod]
public static string InsertData(string username, string subj, string desc)
{
string msg = string.Empty;
using (SqlConnection con = new SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd = new SqlCommand("insert into sampleinfo(name,subject,description) VALUES(@name,@subject,@desc)", con))
{
con.Open();
cmd.Parameters.AddWithValue("@name", username);
cmd.Parameters.AddWithValue("@subject", subj);
cmd.Parameters.AddWithValue("@desc", desc);
int i = cmd.ExecuteNonQuery();
con.Close();
if (i == 1)
{
msg = "true";
}
else
{
msg = "false";
}
}
}
return msg;
}

VB.NET Code


Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridviewData()
End If
End Sub
Protected Sub BindGridviewData()
Using con As New SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("select * from sampleinfo", con)
con.Open()
Dim ds As New DataSet()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
End Using
End Using
End Sub
<WebMethod()> _
Public Shared Function InsertData(ByVal username As String, ByVal subj As String, ByVal desc As String) As String
Dim msg As String = String.Empty
Using con As New SqlConnection("Data Source=Suresh;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("insert into sampleinfo(name,subject,description) VALUES(@name,@subject,@desc)", con)
con.Open()
cmd.Parameters.AddWithValue("@name", username)
cmd.Parameters.AddWithValue("@subject", subj)
cmd.Parameters.AddWithValue("@desc", desc)
Dim i As Integer = cmd.ExecuteNonQuery()
con.Close()
If i = 1 Then
msg = "true"
Else
msg = "false"
End If
End Using
End Using
Return msg
End Function
End Class

Demo


Insert Data into Database using jQuery Ajax Method in Asp.net using C#, VB.NET
Download Sample Code Attached




If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

4 comments :

Jayesh said...

Bootstrap validation not working using [input type="button"]. By using [input type="submit"] works well but do random insertion.

vishal blog said...
This comment has been removed by the author.
Shailesh Waghule said...

Thanks, It is very usefull for me

Sudam Tambe said...

Not working properly this code not insert in database

Give your Valuable Comments

Other Related Posts

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.