原文作者:杨友山
原文地址:http://blog.csdn.net/yysyangyangyangshan/article/details/22438077
前面看了如何增加和删除Gridview数据,但是无论怎样Gridview的数据除了展示给用户外,还需要进行编辑后保存的。
也就是将Gridview的数据获取下来传到后台,然后后台经过识别和处理获得数据,保存至数据库中。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> </head> <body id="Body1" runat="server"> <form id="Form1" runat="server"> <asp:Button ID="btnAdd" runat="server" OnClientClick="return SaveBatch();return false;" Text="批量保存"/> <asp:GridView ID="dgPersons" runat="server" EnableViewState="false" CellPadding="4" GridLines="Horizontal" PageChange="TextBox" AutoGenerateColumns="False" SortMode="Total" ForeColor="#333333" CellSpacing="1" Width="60%" ShowNoRecordTip="True"> <Columns> <asp:TemplateField> <ItemTemplate> <%#Container.DataItemIndex +1%> <input id="hideID" type="hidden" runat="server" value='<%#Eval("p_id")%>' /> </ItemTemplate> <HeaderTemplate> <span>序号</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <span> <%#Eval("p_name")%></span> </ItemTemplate> <HeaderTemplate> <span>姓名</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <span> <%#Eval("p_age")%></span> </ItemTemplate> <HeaderTemplate> <span>年龄</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <span> <%#Eval("p_sex")%></span> </ItemTemplate> <HeaderTemplate> <span>性别</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="txtRemark" runat="server" Text='<%#Eval("p_remark")%>' Width="120px" Height="30px"/> </ItemTemplate> <HeaderTemplate> <span>备注</span> </HeaderTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <a href ="JavaScript:viod(0)" onclick="javascript:SaveSingle(this)">保存</a> </ItemTemplate> <HeaderTemplate> <span>操作</span> </HeaderTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" HorizontalAlign="Center" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <RowStyle HorizontalAlign="Center" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView> </form> </body> <script type="text/javascript" src="/Scripts/Ajax.js"></script> <script type="text/javascript" src="/Scripts/jquery-1.4.1.js"></script> <script language="javascript" type="text/javascript"> var dgPersonsID = "<%= dgPersons.ClientID %>"; $(document).ready(function () { $("#dgPersons tr").eq(1).hide(); }); function GetGridViewDatas() { var dgs = document.getElementById(dgPersonsID); if (dgs.rows == null || dgs.rows.length < 2) { alert("没有数据!"); return; } var gridobj = new Object(); gridobj.ID = dgs.rows[1].cells[0].children[0].value; gridobj.Name = dgs.rows[1].cells[1].children[0].innerHTML; gridobj.Age = dgs.rows[1].cells[2].children[0].innerHTML; gridobj.Sex = dgs.rows[1].cells[3].children[0].innerHTML; gridobj.Remark = dgs.rows[1].cells[4].children[0].value; for (var i = 2; i < dgs.rows.length; i++) { gridobj.ID += "," + dgs.rows[i].cells[0].children[0].value; gridobj.Name += "," + dgs.rows[i].cells[1].children[0].innerHTML; gridobj.Age += "," + dgs.rows[i].cells[2].children[0].innerHTML; gridobj.Sex += "," + dgs.rows[i].cells[3].children[0].innerHTML; gridobj.Remark += "," + dgs.rows[i].cells[4].children[0].value; } return gridobj; } //批量保存 function SaveBatch() { var gridDatas = GetGridViewDatas(); var saveDatas = gridDatas; saveDatas.operateType = "SaveAll"; var htmlObjects = $.ajax({ type: "POST", data: saveDatas, async: true, success: function (result) { if (result != "false") { alert("保存成功!"); } else { alert("保存失败!"); } }, error: function (result) { alert("保存失败!"); } }); return false; } //单个保存 function SaveSingle(obj) { var elm = event.target || event.srcElement; if (elm.disabled) { return false; } var row = obj.parentElement.parentElement; var gridobj = new Object(); gridobj.snID = row.cells[0].children[0].value; gridobj.Name = row.cells[1].children[0].innerHTML; gridobj.Age = row.cells[2].children[0].innerHTML; gridobj.Sex = row.cells[3].children[0].innerHTML; gridobj.Remark = row.cells[4].children[0].value; var saveData = gridobj; saveData.operateType = "SaveSingleData"; var htmlobj = $.ajax({ type: "POST", data: saveData, async: true, success: function (result) { if (result != "false") { alert("保存成功!"); } else { alert("保存失败!"); } }, error: function (result) { alert("保存失败!"); } }); return false; } </script> </html>
public partial class ChildFrm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { switch (Request["operateType"]) { case "SaveAll": SaveAllData(); return; case "SaveSingleData": SaveSingleData(); return; default: break; } if (!IsPostBack) { DataTable dt = InitData(); this.dgPersons.DataSource = dt; this.dgPersons.DataBind(); } } private DataTable InitData() { DataTable PersonCollect = new DataTable(); PersonCollect = new DataTable(); PersonCollect.Columns.Add("p_id"); PersonCollect.Columns.Add("p_name"); PersonCollect.Columns.Add("p_age"); PersonCollect.Columns.Add("p_sex"); PersonCollect.Columns.Add("p_remark"); if (PersonCollect.Rows.Count < 1) { for (int i = 0; i < 11; i++) { DataRow nrow = PersonCollect.NewRow(); nrow["p_id"] = System.Guid.NewGuid().ToString(); nrow["p_name"] = "西北白杨树"; nrow["p_age"] = 27; nrow["p_sex"] = "男"; nrow["p_remark"] = string.Empty; PersonCollect.Rows.Add(nrow); } } return PersonCollect; } protected void SaveSingleData() { string id = Request["snID"].ToString().Trim() ; string name = Request["Name"].ToString().Trim(); string age = Request["Age"].ToString().Trim(); string sex = Request["Sex"].ToString().Trim(); string remark = Request["Remark"].ToString().Trim(); bool savesuccess = true; //获取到了list拿到数据库去保存吧,然后将是否保存成功赋值给savesuccess,前台根据这个变量来提示 //这里是要生成一个json字符串给前台提示用 //可以多加几个属性,让提示内容更丰富 ArrayList list = new ArrayList(); Hashtable ht = new Hashtable(); ht.Add("Success", savesuccess.ToString().ToLower()); list.Add(ht); JavaScriptSerializer json = new JavaScriptSerializer(); string jsonResult = json.Serialize(list); SendTextMessage(jsonResult); } protected void SaveAllData() { string id = Request["ID"].ToString(); string name = Request["Name"].ToString(); string age = Request["Age"].ToString(); string sex = Request["Sex"].ToString(); string remark = Request["Remark"].ToString(); string[] ids = SplitString(id); string[] names = SplitString(name); string[] ages = SplitString(age); string[] sexs = SplitString(sex); string[] remarks = SplitString(remark); List<Person> resultList = new List<Person>(); if (ids != null && ids.Length > 0) { for (int i = 0; i < ids.Length; i++) { Person m = new Person(); m.ID = ids[i]; m.Name = names[i]; m.Age = ages[i]; m.Sex = sexs[i]; m.Remark = remarks[i]; resultList.Add(m); } } bool savesuccess = true; //获取到了list拿到数据库去保存吧,然后将是否保存成功赋值给savesuccess,前台根据这个变量来提示 //这里是要生成一个json字符串给前台提示用 //可以多加几个属性,让提示内容更丰富 ArrayList list = new ArrayList(); Hashtable ht = new Hashtable(); ht.Add("Success", savesuccess.ToString().ToLower()); list.Add(ht); JavaScriptSerializer json = new JavaScriptSerializer(); string jsonResult = json.Serialize(list); SendTextMessage(jsonResult); } private string[] SplitString(string value) { if (string.IsNullOrEmpty(value)) { return new string[0]; } return value.Split(','); } private List<Results> GetResults(bool result,string message) { List<Results> response = new List<Results>(); Results r = new Results(); r.Success = result.ToString().ToLower(); r.Message = message; response.Add(r); return response; } protected void SendTextMessage(string message) { Response.ContentType = "text/plain"; Response.Write(message); Response.End(); } }单行封装为一个实体
public class Person { private string id; public string ID { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string age; public string Age { get { return age; } set { age = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } private string remark; public string Remark { get { return remark; } set { remark = value; } } }