Introduction
Most web applications are using AJAX to create more responsive Web applications. AJAX makes the response time faster. In some web applications the set of values from the grid are required to pass at one instance and the same is required to be saved in the database.
In this article, I will explain how to pass and save the set of values from the grid/tables using AJAX with a simple C# example.
Step 1
Create ASP.NET page and add a grid to the page.
To add Grid in the Page,
<asp:GridView ID="itemsToAddinGrid" CssClass="table" runat="server" AutoGenerateColumns="false" OnRowDataBound="itemsToAddinGrid_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Value A" ItemStyle-Width="100px" ItemStyle-CssClass="ValueA">
<ItemTemplate>
<%# Eval("ValueA")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value B" ItemStyle-Width="100px" ItemStyle-CssClass="ValueB">
<ItemTemplate>
<%# Eval("ValueB")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value C" ItemStyle-Width="100px" ItemStyle-CssClass="ValueC">
<ItemTemplate>
<%# Eval("ValueC")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value D" ItemStyle-Width="100px" ItemStyle-CssClass="ValueD">
<ItemTemplate>
<%# Eval("ValueD")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Step 2: Add values to grid using JavaScript
Below code is to add values to grid from textbox using JavaScript,
function AddToGrid() {
var gridView = document.getElementById("<%=itemsToAddinGrid.ClientID %>");
var tbody = gridView.getElementsByTagName("tbody")[0];
var row = tbody.getElementsByTagName("tr")[1];
//Check if row is dummy, if yes then remove.
if (row.getElementsByTagName("td")[0].innerHTML.replace(/\s/g, '') == "") {
tbody.removeChild(row);
}
row = row.cloneNode(true);
//Add the Name value to first cell.
var iValA = document.getElementById("<%=TextBox1.ClientID %>");
SetValue(row, 0, "iValA", iValA);
var iValB = document.getElementById("<%=TextBox2.ClientID %>");
SetValue(row, 1, "iValB", iValB);
var iValC = document.getElementById("<%=TextBox3.ClientID %>");
SetValue(row, 2, "iValC", iValC);
var iValD = document.getElementById("<%=TextBox4.ClientID %>");
SetValue(row, 3, "iValD", iValD);
tbody.appendChild(row);
document.getElementById('TextBox1').value = "";
document.getElementById('TextBox2').value = "";
document.getElementById('TextBox3').value = "";
document.getElementById('TextBox4').value = "";
return false;
}
function SetValue(row, index, name, textbox) {
row.cells[index].innerHTML = textbox.value;
}
Step 3
Create a page AjaxToRetriveDataWithArray.aspx
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static List < LoEArray > GetRecords(string FuncVal, string[][] gridArray) {
List < LoEArray > list = new List < LoEArray > ();
if (FuncVal == "SaveGridRecordsToDB") {
SqlConnection con = new SqlConnection("User ID=ID;Initial Catalog=DatabaseName;Data Source=ServerName");
con.Close();
con.Open();
for (int i = 0; i < gridArray.GetLength(0); i++) {
string ValueA = gridArray[i][0].ToString().Trim();
string ValueB = gridArray[i][1].ToString().Trim();
string ValueC = gridArray[i][2].ToString().Trim();
string ValueD = gridArray[i][3].ToString().Trim();
SqlCommand com = new SqlCommand("insert into ValuetoAdd values('" + ValueA.Trim().Replace("'", "''").ToString() + "','" + ValueB.Trim().Replace("'", "''").ToString() + "','" + ValueC.Trim().Replace("'", "''").ToString() + "','" + ValueD.Trim().Replace("'", "''").ToString() + "')", con);
com.ExecuteNonQuery();
}
con.Close();
LoEArray obj = new LoEArray();
obj.Id = "1";
obj.Name = "Records Saved";
list.Add(obj);
}
return list;
}
public class LoEArray {
public string Id {
get;
set;
}
public string Name {
get;
set;
}
public string Code {
get;
set;
}
public string Category {
get;
set;
}
}
Step 4
Save Grid Records using AJAX
function SaveGridRecords() {
var myGrid = document.getElementById("<%=itemsToAddinGrid.ClientID %>");
var oRows = myGrid.rows;
var k;
var gridArray = [];
for (k = 1; k < oRows.length; k++) {
gridArray[k - 1] = [];
var currentRow = myGrid.rows[k];
gridArray[k - 1][0] = currentRow.cells[0].innerHTML;
gridArray[k - 1][1] = currentRow.cells[1].innerHTML;
gridArray[k - 1][2] = currentRow.cells[2].innerHTML;
gridArray[k - 1][3] = currentRow.cells[3].innerHTML;
}
$.ajax({
type: "POST",
url: "AjaxToRetriveDataWithArray.aspx/GetRecords",
data: JSON.stringify({
FuncVal: "SaveGridRecordsToDB",
gridArray: gridArray
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$.each(data, function() {
$.each(this, function(k, v) {
alert(v.Name);
});
});
},
failure: function(response) {
alert(response.d);
}
});
}