Json数据格式,简单而强大。
使用Json,不得不提到Newtonsoft.Json,它帮助我们更方便的使用Json,当然,不使用它也是可以的,还有许多方法将对象序列化成Json字符串,暂且不提。
我使用Json主要是在两个方面:
第一,在后台代码,用JsonConvert.SerializeObject()方法将对象序列化成字符串对象,然后在前台代码中,再用Json.Parse()方法反序列成javascript对象,然后处理对象;这种情况往往是在读数据库时会需要的,例如,列表页面;
第二,在前台代码,将javascript对象利用Json.stringify()方法序列化成字符串,然后传输到,后台代码中,再用JsonConvert.DeserializeObject<T>()方法反序列化成对象,然后处理对象;这种情况往往是在往数据库增加或者修改数据时需要的,例如,增加页面;
在这个过程中,需要注意的是:
1、在后台定义的对象与前台定义的对象,名称要相同,大小可以不一样;
另外需要啰嗦两句的是,我写的示例功能都是从公司的项目中,抽出来的一点功能点,然后用自己的想法来操作实现的,通过这样的练习,才可以慢慢地提高自己;另外,每个练习都是认真的按照大项目的编码规范去做的,例如,项目命名规范;编辑命名规范等等。
本示例主要是实现了上面两个方法:显示数据和保存数据,注意没有连接数据库,只是传输一下数据而已。
好吧,下面就不废话,贴上代码说明问题:
CodeSetupEdit.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CodeSetupEdit.aspx.cs" Inherits="CodeSetup.CodeSetupEdit" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="js/jquery-1.9.1.js"></script> <script src="js/ajaxhelper.js"></script> <script> $(document).ready(function () { ajaxmethod("../Handler/CodeSetupHandler.ashx?actiontype=getlist", function (data) { var obj = JSON.parse(data); $("#txtContext").val("编码选项是:" + obj.CodeOption + ";占位符是:" + obj.PlaceHolder + ";长度是:" + obj.Length + ";是否连号:" + obj.IsNeedContinuous); }); }); var CodeSetup = function (codeoption, placeholder, length, isneedcontinuous) { this.CodeOption = codeoption, this.PlaceHolder = placeholder, this.Length = length, this.IsNeedContinuous = isneedcontinuous } function save() { var url = "../Handler/CodeSetupHandler.ashx?actiontype=save"; var codesetupEntity = new CodeSetup(1, "yyyy", 3, 1); $.post(url, { CodeSetupEntity: JSON.stringify(codesetupEntity), }, function (data) { }, "text"); } </script> </head> <body> <form id="form1" runat="server"> <div> <textarea id="txtContext" style="height: 50px; 300px;"></textarea> <input type="button" id="btnSave" value="保存" onclick="save()" /> </div> </form> </body> </html>
CodeSetupHandler.ashx
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; using System.Web.UI.WebControls; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CodeSetup.Handler { /// <summary> /// CodeSetupHandler 的摘要说明 /// </summary> public class CodeSetupHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string action = context.Request["actiontype"] ?? context.Request["actiontype"].ToString(); switch (action) { case "getlist": context.Response.Write(GetModel()); break; case "save": Save(); break; default: break; } } public string GetModel() { var codeSetup = new CodeSetup() { CodeOption = (int)CodeOptionType.Date, IsNeedContinuous = 0, Length = 0, placeHolder = ((int)DateType.YYYYMMDD).ToString() }; return JsonConvert.SerializeObject(codeSetup); } public void Save() { string codesetupentity = HttpContext.Current.Request.Form["CodeSetupEntity"]; JObject o = JObject.Parse(codesetupentity.ToString()); //string codeoption = o["CodeOption"].ToString(); //string placeholder = o["PlaceHolder"].ToString(); //string length = o["Length"].ToString(); //string isneedcontinuous = o["IsNeedContinuous"].ToString(); CodeSetup codeSetup = JsonConvert.DeserializeObject<CodeSetup>(codesetupentity); } public bool IsReusable { get { return false; } } } public class CodeSetup { public int CodeOption { get; set; } public string placeHolder { get; set; } public int Length { get; set; } public int IsNeedContinuous { get; set; } } public enum CodeOptionType { /// <summary> /// 自定义 /// </summary> [Description("自定义")] Define = 0, /// <summary> /// 日期 /// </summary> [Description("日期")] Date = 1, /// <summary> /// 分隔符 /// </summary> [Description("分隔符")] Separator = 2, /// <summary> /// 流水号 /// </summary> [Description("流水号")] Number = 3, } public enum DateType { /// <summary> /// 年月日 /// </summary> [Description("年月日")] YYYYMMDD = 0, /// <summary> /// 年月 /// </summary> [Description("年月")] YYYYMM = 1, /// <summary> /// 年 /// </summary> [Description("年")] YYYY = 2, /// <summary> /// 月 /// </summary> [Description("月")] MM = 3, /// <summary> /// 日 /// </summary> [Description("日")] DD = 3, } public enum SeparatorType { /// <summary> /// _ /// </summary> [Description("下划线")] Underline = 0, /// <summary> /// - /// </summary> [Description("短横线")] Hyphen = 1, } /// <summary> /// 枚举工具类 /// </summary> public sealed class EnumUtil { private static Dictionary<string, Dictionary<int, string>> _EnumList = new Dictionary<string, Dictionary<int, string>>(); //枚举缓存池 /// <summary> /// 将枚举绑定到ListControl /// </summary> /// <param name="listControl">ListControl</param> /// <param name="enumType">枚举类型</param> public static void FillListControl(ListControl listControl, Type enumType) { listControl.Items.Clear(); listControl.DataSource = EnumToDictionary(enumType); listControl.DataValueField = "key"; listControl.DataTextField = "value"; listControl.DataBind(); } /// <summary> /// 将枚举转换成Dictionary<int, string> /// Dictionary中,key为枚举项对应的int值;value为:若定义了EnumShowName属性,则取它,否则取name /// </summary> /// <param name="enumType">枚举类型</param> /// <returns></returns> public static Dictionary<int, string> EnumToDictionary(Type enumType) { string keyName = enumType.FullName; if (!_EnumList.ContainsKey(keyName)) { Dictionary<int, string> list = new Dictionary<int, string>(); foreach (int i in Enum.GetValues(enumType)) { string name = Enum.GetName(enumType, i); //取显示名称 string showName = string.Empty; object[] atts = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false); if (atts.Length > 0) showName = ((DescriptionAttribute)atts[0]).Description; list.Add(i, string.IsNullOrEmpty(showName) ? name : showName); } object syncObj = new object(); if (!_EnumList.ContainsKey(keyName)) { lock (syncObj) { if (!_EnumList.ContainsKey(keyName)) { _EnumList.Add(keyName, list); } } } } return _EnumList[keyName]; } /// <summary> /// 获取枚举值对应的显示名称 /// </summary> /// <param name="enumType">枚举类型</param> /// <param name="intValue">枚举项对应的int值</param> /// <returns></returns> public static string GetDescription(Type enumType, int intValue) { return EnumToDictionary(enumType)[intValue]; } } }
贴完代码后,才发现里面还有几段代码与写的这个示例是不相关的,主要是枚举的一个工具类,这个大家可以忽略就行。