搞了老半天,為了接JavaScript的Json格式,轉成Server端(C#)的Dictionary集合會有問題, List集合好像沒問題,先用這個方式解決,此範例模疑一個Model裡有這2種集合傳遞。

JQuery:

        $(function () {
            $("#send").click(function () {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Index")',
                    data: JSON.stringify(GetData()),
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        alert(result.d);
                    },
                    error: function (result) {
                        alert("Error:" + result.toString());
                    }
                });
            });

            function GetData() {

                var array = new Array();
                var wdata =
                {
                    Name: "Cool",
                    Comment: "酷"
                };
                array.push(wdata);

                var Idata =
                {
                    "p1": "pic1.jpg",
                    "p2": "pic2.png"
                };

                var data =
                {
                    ID: "1",
                    Name: "Jimmy",
                    ImageString: JSON.stringify(Idata),
                    Words: array
                };
                return data;
            };
        });

MVC Controller接值:

        [HttpPost]
        public ActionResult Index(Articles article)
        {
            //方法1-使用JavaScriptSerializer物件,進行反序列化
            var ser = new JavaScriptSerializer();
            article.Images = ser.Deserialize>(article.ImageString);

            //方法2-使用Json.NET進行反序列化
              article.Images = JsonConvert.DeserializeObject>(article.ImageString);

            return new EmptyResult();
        }

MVC Models定義:

    public class Articles
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public Dictionary<string, string> Images { get; set; }

        public string ImageString { get; set; }

        public List<Word> Words { get; set; }
    }
//==================================================================//
    public class Word
    {
        public string Name { get; set; }

        public string Comment { get; set; }
    }
文章標籤
創作者介紹

吉米.NET

Jimmy 發表在 痞客邦 留言(0) 人氣()