最近做的一個小項目中需要將json數組數據傳遞到服務器端進行保存,現分享一下解決思路。
環境:EasyUi+Mvc 4.0
如下:
在上述截圖中的紅色圈起來的部分,需要在點擊保存后通過一次ajax請求,完成數據保存。
很多項目都存在這樣的需求,所以了解解決辦法很重要。
分析過程:
紅色圈起部分分兩塊,一塊是圖片,包含字段“圖片路徑”和“圖片說明”,可以推斷出json數據格式{'圖片路徑':xxx,'圖片說明':xxx}。
一塊是子物料集合,包含字段“子物料編號”和“備注”,可以推斷出json格式{'子物料編號':xxx,'備注':xxx}。
然而這兩塊的數據是多條的,所以想到用js“[]”(js數組)進行存儲。
也就是可以寫出如下代碼:
//圖片實體 與后台屬性一致 function Part_Pic(ImgDescription, ImgUrl) { this.ImgDescription = ImgDescription; this.ImgUrl = ImgUrl; return this; } //子物料實體 與后台屬性一致 function Part_Children(ChildMaterialNumber, Remark) { this.ChildMaterialNumber = ChildMaterialNumber; this.Remark = Remark; return this; } //有一個函數用來取數據並填充至數組內 function Save() { var Part_PicList = []; //定義圖片數組,用於存放多條圖片信息 var Part_ChildrenList = []; //定義子物料數組 //接下來拿到數據並填充,以下為范例 var PartPicObj=new Part_Pic('這是圖片描述','這是圖片鏈接'); Part_PicList.push(PartPicObj); //填充 }
好了,接下來有個關鍵的地方,就是如何把這兩個js數組傳遞到服務端並解析。
這里用到了json的序列化和反序列化知識。
一般的ajax請求如下:
$.ajax({ url: "/Part/Get_Details", type: "POST", dataType: "json", data: { "ID": row["ID"] }, success: function (res) { //該干嘛干嘛 }, error: function (error) { alert(JSON.stringify(error)); } });
對於“data”,直接傳遞js數組的話,服務端接收到的是這么個東西 “[object,object]”,可見服務端根本不認識它。
好在js有個序列化函數,將對象序列化為“json字符串”。
JSON.stringify(WorkList) //微軟官方解釋:https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx
也就是說將“js數組”通過該函數序列化后創建了新的“字符串”。“字符串”對於服務器端來說不管哪種語言都是可以識別的。
那么ajax請求就可以這么寫:
$.ajax({ url: "/Part/Get_Details", type: "POST", dataType: "json", data:
{ "ID": row["ID"] , "Part_ChildrenList":JSON.stringify(Part_ChildrenList) //序列化 }, success: function (res) { //該干嘛干嘛 }, error: function (error) { alert(JSON.stringify(error)); //這個地方也用到了 } });
好了,接下來要解決的問題就是如何在服務端進行解析,用到了對象反序列化。
我這里用到的是Newtonsoft.Json,在MVC4.0的項目中是默認引用的。
Newtonsoft.Json.JsonConvert是一個微軟的免費json轉換工具。
Newtonsoft.Json 是.NET 下開源的json格式序列號和反序列化的類庫.
List<實體> listwork = new List<實體>(); listwork = Newtonsoft.Json.JsonConvert.DeserializeObject<List<實體>>("前台傳過來的json字符串");
就是這么一句話就完成了json字符串的反序列化。ps:真是簡單。
至此,就有了完全的解決思路,接下來就是擼代碼的工作了。
部分代碼:

//圖片實體 與后台屬性一致 function Part_Pic(ImgDescription, ImgUrl) { this.ImgDescription = ImgDescription; this.ImgUrl = ImgUrl; return this; } //子物料實體 與后台屬性一致 function Part_Children(ChildMaterialNumber, Remark) { this.ChildMaterialNumber = ChildMaterialNumber; this.Remark = Remark; return this; } //保存 function SaveEntity() { //定義圖片集合 var Part_PicList = []; $.each($("#yulan_div").find("div"), function () { var desobj = $(this).find("input[name='ImgDescription']"); var urlobj = $(this).find("div").find("img[name='ImgUrl']"); if (desobj.length > 0 && urlobj.length > 0) { var picobj = new Part_Pic(desobj.val(), urlobj.attr("src")); Part_PicList.push(picobj); //填充數組 } }); //定義子物料集合 var Part_ChildrenList = []; $.each($("#childrentable tbody tr"), function () { var childrenobj = new Part_Children(); var tdObj = $(this).find("td"); $.each(tdObj, function (index) { //是否有文本框 var hasText = tdObj.find("input[type='text']").length; if (hasText <= 0) { //子物料編號 if (index == 1) { childrenobj.ChildMaterialNumber = $(this).html(); } else if (index == 2)//備注 { childrenobj.Remark = $(this).html(); } } }); if (childrenobj.ChildMaterialNumber != undefined) { Part_ChildrenList.push(childrenobj);//填充數組 } }); $('#fmDetail').form('submit', { url: "/Part/Save", onSubmit: function (param) { //提交時觸發 //easyui提交時增加參數 param.Part_PicList = JSON.stringify(Part_PicList);//關鍵點,對數組進行json序列化,不然無法傳遞到服務端 param.Part_ChildrenList = JSON.stringify(Part_ChildrenList); var flag = $(this).form('validate'); //是否通過驗證 if (flag) { $('#grid').datagrid("loading"); //如果通過驗證讓datagrid顯示載入狀態 } return flag; }, success: function (res) { if (res == "ok") { $.messager.show({ title: '操作提示', msg: '<img src="/images/icons/bigyes.png" /> 保存成功', timeout: 2000, showType: 'slide' }); $('#DivAdd').dialog('close'); //關閉彈出框 $('#fmDetail').form('clear'); //清除表單數據。 $('#btnSearch').click(); //重新加載數據 } else { $.messager.show({ title: '錯誤提示', msg: '<img src="/images/icons/bigno.png" /> 保存失敗!請聯系管理員或嘗試重新操作。', timeout: 0, width: 320, showType: 'slide' }); } } }) }

public void SetChildren(PartView entity) { entity.Part_PicList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Part_Pic>>(Request["Part_PicList"]); entity.Part_ChildrenList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Part_Children>>(Request["Part_ChildrenList"]); bool resultchild = Part_ChildrenBLL.Instance.Where("PartID=@PartID").Parms(entity.ID) .Update("IsDel=1"); if (resultchild) { foreach (var item in entity.Part_ChildrenList) { item.PartID = entity.ID; Part_ChildrenBLL.Instance.Add(item, new string[] { "PartID", "ChildMaterialNumber", "Remark" }); } } bool resultpic = Part_PicBLL.Instance.Where("PartID=@PartID").Parms(entity.ID) .Update("IsDel=1"); if (resultpic) { foreach (var item in entity.Part_PicList) { item.PartID = entity.ID; Part_PicBLL.Instance.Add(item, new string[] { "PartID", "ImgUrl", "ImgDescription" }); } } }
文筆不佳,請多多指教。
勤奮是一種生活態度,你如何對待生活,生活就如何對待你
↓↓↓掃描下面的二維碼,關注我的公眾號