ASP.NET—007:GridView資料的儲存($.ajax實現前後臺互動)
阿新 • • 發佈:2019-02-06
原文作者:楊友山
前面看了如何增加和刪除Gridview資料,但是無論怎樣Gridview的資料除了展示給使用者外,還需要進行編輯後儲存的。
也就是將Gridview的資料獲取下來傳到後臺,然後後臺經過識別和處理獲得資料,儲存至資料庫中。主要原理還是前面的$.ajax方式傳資料。要用到的就是JS的物件了。傳到後臺的是字串,經過擷取,獲得資料。
這裡需要做一個準備工作,安裝asp.net ajax ,因為專案中的關於json的操作需要用到
C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025下的
System.Web.Extensions.dll和System.Web.Extensions.Design.dll,
直接上程式碼,重要的程式碼還是JS獲取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; }
}
}
效果如下,
單行儲存
批量儲存,後臺獲取的值給實體
程式碼下載:http://download.csdn.net/detail/yysyangyangyangshan/7114605