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.
Description:
In previous articles I explained read xml file and bind data to gridview in asp.net, Delete multiple rows in gridview using checkbox in asp.net, bind dropdownlist in asp.net gridview using dataset, cascading dropdownlist in gridview using asp.net, change gridview header dynamically in asp.net and many articles relating to gridview, asp.net, c#,vb.net and jQuery. Now I will explain how to insert data into database using jQuery in asp.net using c#, vb.net.
In previous articles I explained read xml file and bind data to gridview in asp.net, Delete multiple rows in gridview using checkbox in asp.net, bind dropdownlist in asp.net gridview using dataset, cascading dropdownlist in gridview using asp.net, change gridview header dynamically in asp.net and many articles relating to gridview, asp.net, c#,vb.net and jQuery. Now I will explain how to insert data into database using jQuery 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
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. |
|||
|
|||
7 comments :
Bootstrap validation not working using [input type="button"]. By using [input type="submit"] works well but do random insertion.
Thanks, It is very usefull for me
Not working properly this code not insert in database
cant get it to work
It is very use full
It is very Good Topic
Note: Only a member of this blog may post a comment.