Json在asp.net开发中的应用
一、asp.net后台返回Json数据,前台js解析
在后台读取数据,并手动封装成Json格式:
public ContentResult getUsersByOrgId(int Id) { DataTable table = UsersLogic.getUsersByOrgId(Id); StringBuilder data = new StringBuilder(); foreach (DataRow row in table.Rows) { data.Append(",{"); data.Append("\"UserId\":\"" + row["UserId"] + "\","); data.Append("\"UserName\":\"" + row["UserName"] + "\""); data.Append("}"); } if (data.Length > 0) data = data.Remove(0, 1); string result = "{\"items\":[" + Convert.ToString(data) + "]}"; return Content(result, "application/json"); }
在前台用js解析,并展示到页面:
function GetOrgUsers(Id) { $.post("/StockManage/Ware/getUsersByOrgId", { Id: Id }, function (data) { var rJson = JSON.parse(JSON.stringify(data)); //转为josn数据 if (rJson != "" && rJson != null && rJson != "undefined") { var htmlData = ""; for (m = 0; m < rJson.items.length; m++) { var uid = rJson.items[m]["UserId"]; var uname = rJson.items[m]["UserName"]; htmlData += "<option value='" + uid + "'>" + uname + "</options>"; } $("#Select").html(htmlData); } return; }); }
二、js封装Json数据,传给后台解析
js封装Json数组:
var arr = []; var jsonObj = {}; jsonObj.UserId= 2; jsonObj.UserName= "Hellow World!"; jsonObj.Phone= "10086100101"; arr.push(jsonObj); $.post('/UserArea/User/SaveData', { "param": JSON.stringify(arr) }, function (data) { Success(data); });
ASP.NET后台解析:
#region 控制器接收数据 public JsonResult SaveData(string param) {
try { UserLogic.AddConstruct(param); return Json(new { Result = "OK", Message = "操作成功" }); } catch (Exception ex) { return Json(new { Result = "ERROR", Message = ex.Message }); } } #endregion #region 保存数据到数据库 public static bool AddConstruct(string json) { bool status = false; try { JArray jObject = (JArray)JsonConvert.DeserializeObject(json); for (int i = 0; i < jObject.Count; i++) { User cs = new User(); var tmpObj = (JObject)jObject[i]; cs.UserId= Convert.Int(tmpObj["UserId"]); cs.UserName= tmpObj["UserName"].ToString(); cs.Phone= tmpObj["Phone"].ToString();//向主表插入数据 UserContext.Instance.Insert(cs); } status = true; } catch { status = false; } return status; } #endregion