json格式后台转换使用
ashx.cs中需要的工作:
一般处理程序中使用Session:如果想要在ashx中应用Session则必须先引入一个头文件using System.Web.SessionState;然后public class JsonHandler : IHttpHandler, IRequiresSessionState/*IRequiresSessionState是新添加的,需要实现这个接口才能使用Session*/{public void Proce***equest(HttpContext context){HttpContext.Current.Response.CacheControl = "no-cache";string name = context.Session["Name"].ToString(); /*注意这里需要加上context*/}}一般处理程序当中清除浏览器缓存:HttpContext.Current.Response.CacheControl = "no-cache"; /*意思就是把当前响应中的缓存设置为不缓存,即为清除缓存!一般是加在最前面*/将DataSet类型的数据转化为JSON格式的数据:public static string ToJson(DataTable dt) //将DataSet类型的数据转化为JSON格式的数据{ StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append("["); for (int i = 0; i < dt.Rows.Count; i++) { jsonBuilder.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append("\""); jsonBuilder.Append(dt.Columns[j].ColumnName); jsonBuilder.Append("\":\""); jsonBuilder.Append(dt.Rows[i][j].ToString()); jsonBuilder.Append("\","); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); return jsonBuilder.ToString();} public static string ToJson(DataSet ds){ StringBuilder json = new StringBuilder(); foreach (DataTable dt in ds.Tables) { json.Append("{\""); json.Append(dt.TableName); json.Append("\":"); json.Append(ToJson(dt)); json.Append("}"); } return json.ToString();}声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。