How to bind data in gridview using Jquery
#1. First of all create the html page or .aspx page than create a table in html. Then write the JavaScript code using ajax.
The following code you can see or you can paste the code in head tag:
<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function(){
Demo.loadData();
});
function cleartext()
{
document.getElementById('txtContact').value = "";
document.getElementById('txtCompany').value = "";
}
function addCustomer1()
{
contact = document.getElementById('txtContact').value;
company = document.getElementById('txtCompany').value;
if(contact.length != 0)
{
if(company.length != 0)
{
Demo.AddCustomer(contact,company);
cleartext();
}
}
}
</script>
<script type="text/javascript">
Demo = {};
//how to bind gridview using jquery in table form
Demo.loadData = function () {
Demo.AjaxRequest("AjaxServices.asmx/GetCustomer","{}",function(result){
//alert(result);
var results = eval('(' + result.d + ')');
var dd = '';
dd += '<table cellspecing="0" cellpadding="0" class="test">';
dd += '<th>Customer Id</th><th>Contact Name</th><th>Company Name</th>';
for(var i = 0; i < results.length ; i++)
{
dd += '<tr><td>' + results[i].CustomerId + '</td><td>' + results[i].ContactName + '</td><td>' + results[i].CompanyName + '</td>';
dd += '</tr>';
}
dd += '</table>';
$('#demo').empty()
.html(dd)
.slideDown('slow',function() {
window.scrollTo(0, $('#demo').height())
});
},function(){
alert('Error');
});
}
//how to add data using jquery
Demo.AddCustomer = function (contact, company) {
Demo.AjaxRequest("AjaxServices.asmx/AddCustomer","{'contact':'" + contact + "','company':'" + company + "'}",function(result){
var results = ('(' + result.d + ')');
if(results == '("Success")')
Demo.loadData();
else
alert('sql error');
},function() {
alert('unknown error');
});
}
//Function to cummunicate with database
Demo.AjaxRequest = function (url, param, successfullcallback, errorcallback) {
$.ajax({
type: "POST",
url: url,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successfullcallback,
error: errorcallback
});
}
</script>
#2. Second thing apply styleseet code on the table. Copy the following code and then paste it in head tag:
<style type="text/css">
.test{ width:100%; border-collapse:collapse; border:solid 1px #000; font-size:.95em;}
.test th{background-color:black; color:White; padding:5px; border-left:solid 1px #000; border-bottom:solid 1px #000; }
.test td{ padding:5px;border-left:solid 1px #000; border-bottom:solid 1px #000;}
</style>
#3. Third thing is that create the html form in the page and create a table like this with id.
<table style="border:1px; border-color:Black;">
<tr>
<td>
Contact Name :
</td>
<td>
<input type="text" id="txtContact" />
</td>
</tr>
<tr>
<td>
Company Name :
</td>
<td>
<input type="text" id="txtCompany" />
</td>
</tr>
<tr>
<td>
<input type="button" value="Submit" id="btnSubmit" onclick="addCustomer1()" />
</td>
<td>
<input type="button" value="Reset" id="btnClear" onclick="cleartext()" />
</td>
</tr>
</table>
<div id="demo">
This is a demo grid view.
</div>
#4. Fourth one is that create the webservice.asmx file and write the code to communicate with database. The following code is helpful for you.
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Services;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Serialization;
using System.Data;
/// <summary>
/// Summary description for AjaxServices
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ScriptService()]
public class AjaxServices : System.Web.Services.WebService {
//Add customer in the table
[WebMethod]
public string AddCustomer(string contact, string company)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into Customer(ContactName,CompanyName) Values(@cont,@comp) ", con);
cmd.Parameters.AddWithValue("@cont", contact);
cmd.Parameters.AddWithValue("@comp", company);
con.Open();
int i = (Convert.ToInt32(cmd.ExecuteNonQuery()));
con.Close();
string message = (i == 1) ? "Success" : "Faliur";
return new JavaScriptSerializer().Serialize(message);
}
//The following code Binding the customer table
[WebMethod]
public string GetCustomer()
{
List<Customer> customer = new List<Customer>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from Customer", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adt = new SqlDataAdapter(cmd);
adt.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
Customer newCustomer = new Customer();
newCustomer.CustomerId = Convert.ToInt32(row["CustomerID"].ToString());
newCustomer.ContactName = row["ContactName"].ToString();
newCustomer.CompanyName = row["CompanyName"].ToString();
customer.Add(newCustomer);
}
return new JavaScriptSerializer().Serialize(customer);
}
else
{
return new JavaScriptSerializer().Serialize("no customer");
}
}
}
public class Customer
{
private Nullable<int> customerid = null;
public Nullable<int> CustomerId
{
get { return customerid; }
set { customerid = value; }
}
private string contactname = null;
public string ContactName
{
get { return contactname; }
set { contactname = value; }
}
private string companyname = null;
public string CompanyName
{
get { return companyname; }
set { companyname = value; }
}
}
#5. First of all configure your web.config file for 2.0 frame work. If you work on 3.5 frame work then no problem with this code. And it will be execute successfully.