将class对象转成json对象并通过ajax传递到前端

来源:互联网 发布:艺考生软件缺点 编辑:程序博客网 时间:2024/06/05 20:07

后台代码:

    /// <summary>    /// 测试用的类    /// </summary>    public class Product    {        public int productId { get; set; }        public string productName { get; set; }    }    /// <summary>    /// 测试将各种对象转换成json对象,并返回    /// </summary>    public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        /// <summary>        /// 将实例化类对象转成json对象并返回        /// </summary>        /// <returns></returns>        public JsonResult GetProduct()        {            Product p = new Product            {                productId = 1,                productName = "aaa"            };            JsonResult jr = Json(p);            return jr;        }        /// <summary>        /// 将一组实例化类对象转成json对象并返回        /// </summary>        /// <returns></returns>        public JsonResult GetProducts()        {            List<Product> ps = new List<Product>{                 new Product{productId=111,productName="aaa"},                new Product{productId=333,productName="ccc"}            };            JsonResult jr = Json(ps);            return jr;        }        /// <summary>        /// 将实例化的自定义无名对象转成json对象并返回        /// </summary>        /// <returns></returns>        public JsonResult GetJson()        {            Product p = new Product            {                productId = 111,                productName = "aaa"            };            List<Product> ps = new List<Product> {                 new Product{productId=222,productName="bbb"},                new Product{productId=333,productName="ccc"}            };            JsonResult jr = Json(new            {                msg = "this msg is from GetJson",                product = p,                products = ps            });            return jr;        }        /// <summary>        /// 将datatable转成json对象并返回        /// </summary>        /// <returns></returns>        public JsonResult GetDataTable()        {            DataTable dt = new DataTable();            dt.Columns.Add("id");            dt.Columns.Add("datetime");            DataRow dr = null;            dr = dt.NewRow();            dr[0] = 111;            dr[1] = DateTime.Now;            dt.Rows.Add(dr);            dr = dt.NewRow();            dr[0] = 222;            dr[1] = DateTime.Now.AddDays(1);            dt.Rows.Add(dr);            string datatableJsonStr = DataTableToJsonStr(dt);            JsonResult jr = Json(datatableJsonStr);            return jr;        }        /// <summary>        /// datatable转成json字符串        /// </summary>        /// <param name="dt"></param>        /// <returns></returns>        public string DataTableToJsonStr(DataTable dt)        {            JavaScriptSerializer jss = new JavaScriptSerializer();            jss.MaxJsonLength = int.MaxValue;            ArrayList arrayList = new ArrayList();            Dictionary<string, object> dic = null;            foreach (DataRow dr in dt.Rows)            {                dic = new Dictionary<string, object>();                foreach (DataColumn dc in dt.Columns)                {                    dic.Add(dc.ColumnName, dr[dc.ColumnName].ToString());                }                arrayList.Add(dic);            }            return jss.Serialize(arrayList);        }    }


前端代码:

<script type="text/javascript">    $(function () {        //获取单个实例化对象,并访问其属性        $.ajax({            url: "/Home/GetProduct",            dataType: "json",            cache: false,            data: null,            type: "POST",            success: function (data) {                alert(data.productId + data.productName);            }        });        //获取一组实例化对象,并访问各个对象的属性        $.ajax({            url: "Home/GetProducts",            dataType: "json",            cache: false,            data: null,            type: "Post",            success: function (data) {                alert(data[0].productId + data[0].productName);                alert(data[1].productId + data[1].productName);            }        });        //获取实例化的自定义无名对象,并访问各个属性和对象        $.ajax({            url: "/Home/GetJson",            datatype: "json",            cache: false,            data: null,            type: "post",            success: function (data) {                alert(data.msg);                alert(data.product.productId + data.product.productName);                alert(data.products[0].productId + data.products[0].productName);                alert(data.products[1].productId + data.products[1].productName);            }        });        //获取datatable对象,并访问其中的值        $.ajax({            url: "/Home/GetDataTable",            dataType: "json",            type: "post",            data: null,            cache: false,            success: function (data) {                alert(data);                var rst = $.parseJSON(data);                alert(rst[0].id + rst[0].datetime);                alert(rst[1].id + rst[1].datetime);            }        });    });</script>


将class对象转成json对象并传递到前端时,当class对象的属性为DateTime时,前端获取到的时间格式将是如下:/Date(123456789)/这是原始的时间,js不能直接转成时间变量,所以我们先要把里面的数值取出来,再转成时间变量,然后再读取相应的时间值,如下:<script type="text/javascript">    var t = "/Date(123456789)/";    t = t.replace("/Date(", "").replace(")/", "");    t = new Date(parseInt(t));    alert(t.toLocaleDateString());  //结果:1970年7月2日    alert(t.toLocaleTimeString());  //结果:下午6:17:36    alert(t.toLocaleString());  //结果:1970年7月2日 下午6:17:36</script>我们也可以通过各种get方法来读取相应的时间值。



0 0
原创粉丝点击