using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; namespace SiteCore.Handler { public class GetDicData : BaseHandler, IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/jason"; if (UrlParmsCheck("pType")) { string pType = GetString("pType").ToLower(); string selId = GetString("selId"); int pId = GetInt("pId"); int cur = GetInt("cur"); DataTable dt = null; switch (pType) { case "industry": { dt = WebCache.GetCacheDicData(DicType.Industry, "", "industry_cache"); break; } case "trade": { dt = WebCache.GetCacheDicData(DicType.TradeType, "", "trade_cache"); break; } case "goodstype": { dt = WebCache.GetCacheDicData(DicType.GoodsType, "", "goodstype_cache"); break; } case "producttype": { int mId = GetInt("mId"); dt = WebCache.GetDicData(DicType.ProductType, "MerchantID=" + mId); break; } } if (dt == null) { returnErrorMsg("找不到数据,访问发生错误"); return; } IList selIds = new List(); if (selId != "")//加载己选中的值 { DataRow[] tmpdrs = dt.Select("ID=" + selId); if (tmpdrs != null && tmpdrs.Length > 0) { string path = tmpdrs[0]["Path"].ToString(); path = path.TrimStart('|') + selId; selIds = path.Split('|'); } else { selId = ""; } } DataView dv = new DataView(dt); if (dv.Count > 0) { int idx = 0; IList resultList = new List(); string tag = ""; //如果不是第二次触发&加载己有的值 //if (pId == 0 && selIds.Count > 0) pId = Convert.ToInt32(selIds[0]); TreeBind(dt, pId, ref resultList, ref tag, selIds, idx); //if (selIds.Count > 0) tag = string.Join(",", selIds.ToArray()) + "," + selId; //sel-各级选中的ID,cur-当前选择的第几级触发事件 returnSuccess("{" + string.Format("{0},\"sel\":\"{1}\",\"cur\":{2},\"selId\":\"{3}\"", string.Join(",", resultList.ToArray()), tag.TrimEnd(','), cur, selId) + "}"); } return; } returnErrorMsg("数据读取出错"); } private void TreeBind(DataTable dt, object parentId, ref IList resultList, ref string tag, IList selIds, int idx) { DataView dv = new DataView(dt); if (parentId.ToString() == "") return; dv.RowFilter = "ParentID=" + parentId; string tmp = string.Empty; if (dv.Count > 0) { if (selIds.Count > idx) { tmp = selIds[idx];//下一次加载的ParentID tag += selIds[idx] + ",";//当前默认选中 resultList.Add(string.Format("\"sel{0}\":[{1}]", selIds[idx], DvToJson(dv))); } else { tmp = dv[0]["ID"].ToString();//下一次加载的ParentID tag += tmp + ",";//当前默认选中 resultList.Add(string.Format("\"sel{0}\":[{1}]", tmp, DvToJson(dv))); } TreeBind(dt, tmp, ref resultList, ref tag, selIds, idx + 1); } } private string DvToJson(DataView dv) { StringBuilder json = new StringBuilder(); foreach (DataRowView drv in dv) { json.Append("{"); json.AppendFormat("\"name\":\"{0}\",\"value\":\"{1}\" ", drv["Name"], drv["ID"]); json.Append("},"); } return json.ToString().TrimEnd(','); } } }