[ASP.net教程]生成json格式html頁(yè)面 <input type="button" value="重新生成JSON" class="button1" id="createjson" /> javascript部分 <script type="text/javascript"> $(function () { //生成JSON $("#createjson").click(function () { $.post("NewsCategory.aspx?action=create", function (json) { alert(json.msg); }); }); });</script> 后臺(tái)代碼 protected void Page_Load(object sender, EventArgs e) { if (Request.Headers["X-Requested-With"] != null && Request.Headers["X-Requested-With"].ToLower() == "".ToLower()) { Response.Clear(); Response.ContentType = "application/json"; if (Request["action"] == "create") { Response.Write(CreateJson()); } Response.End(); } } View Code
/// <summary> /// 生成商家類別Json /// </summary> /// <returns></returns> protected string CreateJson() { System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer(); //初始化(引用空間using System.Text;) 漢字轉(zhuǎn)為Unicode編碼 /// <summary> /// 得到漢字的Unicode編碼 /// </summary> protected string GetUnicode(string text) { string result = ""; for (int i = 0; i < text.Length; i++) { if ((int)text[i] > 32 && (int)text[i] < 127) { result += text[i].ToString(); } else result += string.Format("\\u{0:x4}", (int)text[i]); } return result; } View Code 數(shù)據(jù)庫(kù)部分 /// 獲取全部 /// </summary> public List<Model.NewsCategory> Get() { string sql = "select * from NewsCategory order by case when ParentId=0 then Id*10000 else ParentId*10000+Id end"; List<Model.NewsCategory> list = new List<Model.NewsCategory>(); using (SqlDataReader dr = DBUtility.SqlHelper.ExecuteReader(ConnString.connReadonly, CommandType.Text, sql, null)) { while (dr.Read()) { Model.NewsCategory model = new Model.NewsCategory(); object obj; obj = dr["Id"]; if (obj != null && obj != DBNull.Value) { model.Id = (int)obj; } obj = dr["SortValue"]; if (obj != null && obj != DBNull.Value) { model.SortValue = (int)obj; } obj = dr["ParentId"]; if (obj != null && obj != DBNull.Value) { model.ParentId = (int)obj; } model.ItemName = dr["ItemName"].ToString(); model.ItemValue=dr["ItemValue"].ToString(); list.Add(model); } } return list; } View Code 運(yùn)行結(jié)果 [{"id":31,"name":"\u65b0\u95fb\u4e2d\u5fc3","pid":0,"itemvalue":"|0|"}, 涉及的知識(shí)點(diǎn) 1、Server.MapPath(string path); 2、System.IO.File.WriteAllText(sting path,string contents,Encoding encoding); 標(biāo)簽:
|
|