ajax, 通过JSON.stringify(Model)传递对象

直接上实例:

js部分:

1.对象实体

var userInfo={
                            UserID: "@User.UserID", UserName: "@User.UserName", UserRole:"@((int)User.Role)",ClassID: @classid,
                            ClassName:"@ViewBag.ClassModel.ClassName",
                            title: fileObj.name, url: json.info.image, width: json.info.size.width, height: json.info.size.height
                        };


ajax调用:

$.post("/Paint/Create", {userInfo: JSON.stringify(userInfo)}, function (ret) {
                            if(ret==1)
                                $("#formview").append("<input type='hidden' value='" + ret + "' name='pids' />");
                            else if (ret == 2)
                                return dlg.Msg.Err("对不起!您发表的标题包含敏感词,请重新输入!");
                            else if (ret == 3)
                                return dlg.Msg.Err("对不起!您发表的内容包含敏感词,请重新输入!");
                            else if(ret==0)
                                return dlg.Msg.Err("上传失败");
                        });

2.后台程序

实体部分,注意大小写要一致

public class UserInfo
        {
            public int UserID { get; set; }
            public string UserName { get; set; }
            public long ClassID { get; set; }
            public string ClassName { get; set; }
            public int UserRole { get; set; }
            public string title { get; set; }
            public string Content { get; set; }
            public string url { get; set; }
        }
[HttpPost]
        public ActionResult Create(FormCollection collection, string userInfo)
        {
            UserInfo userinfo = new UserInfo();
            userinfo = UtilHelper.ConvertToEntity<UserInfo>(userInfo);
            int userid = userinfo.UserID;
            string username = userinfo.UserName;
            long classid = userinfo.ClassID;
            string classname = userinfo.ClassName;
            int UserRole = userinfo.UserRole;
            var t = userinfo.title;
            var c = userinfo.Content;
            var u = userinfo.url;
       //do something here }

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;

namespace CiWong.Class.Area.Controllers
{
    public static class UtilHelper
    {
        /// <summary>
        /// 生产JSON格式字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonStr<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }
        /// <summary>
        /// 将JSON字符串转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public  static T ToJsonObject<T>(this string str)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(str)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
        #region Json数据转换为泛型集合(或实体)

        /// <summary>
        /// 单条json数据转换为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str">字符窜(格式为{a:'',b:''})</param>
        /// <returns></returns>
        private static T ConvertToEntity<T>(string str)
        {
            Type t = typeof(T);
            object obj = Activator.CreateInstance(t);
            var properties = t.GetProperties();
            string m = str.Trim('{').Trim('}');
            string[] arr = m.Split(',');
            for (int i = 0; i < arr.Count(); i++)
            {
                for (int k = 0; k < properties.Count(); k++)
                {
                    string Name = arr[i].Substring(0, arr[i].IndexOf(":"));
                    object Value = arr[i].Substring(arr[i].IndexOf(":") + 1);
                    if (properties[k].Name.Equals(Name))
                    {
                        if (properties[k].PropertyType.Equals(typeof(int)))
                        {
                            properties[k].SetValue(obj, Convert.ToInt32(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(string)))
                        {
                            properties[k].SetValue(obj, Convert.ToString(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(long)))
                        {
                            properties[k].SetValue(obj, Convert.ToInt64(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(decimal)))
                        {
                            properties[k].SetValue(obj, Convert.ToDecimal(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(double)))
                        {
                            properties[k].SetValue(obj, Convert.ToDouble(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(Nullable<int>)))
                        {
                            properties[k].SetValue(obj, Convert.ToInt32(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(Nullable<decimal>)))
                        {
                            properties[k].SetValue(obj, Convert.ToDecimal(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(Nullable<long>)))
                        {
                            properties[k].SetValue(obj, Convert.ToInt64(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(Nullable<double>)))
                        {
                            properties[k].SetValue(obj, Convert.ToDouble(Value), null);
                        }
                        if (properties[k].PropertyType.Equals(typeof(Nullable<DateTime>)))
                        {
                            properties[k].SetValue(obj, Convert.ToDateTime(Value), null);
                        }

                    }
                }

            }
            return (T)obj;
        }

        /// <summary>
        /// 多条Json数据转换为泛型数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonArr">字符窜(格式为[{a:'',b:''},{a:'',b:''},{a:'',b:''}])</param>
        /// <returns></returns>
        public static List<T> ConvertTolist<T>(this string jsonArr)
        {
            if (!string.IsNullOrEmpty(jsonArr) && jsonArr.StartsWith("[") && jsonArr.EndsWith("]"))
            {
                Type t = typeof(T);
                var proPerties = t.GetProperties();
                List<T> list = new List<T>();
                string recive = jsonArr.Trim('[').Trim(']').Replace("'", "").Replace("\"", "");
                string[] reciveArr = recive.Replace("},{", "};{").Split(';');
                foreach (var item in reciveArr)
                {
                    T obj = ConvertToEntity<T>(item);
                    list.Add(obj);
                }
                return list;
            }
            return null;

        }
        #endregion
    }
}

 

posted @ 2013-03-01 15:44  jchdtxz  阅读(13200)  评论(0编辑  收藏  举报