1. 程式人生 > >Web頁面物件傳值Demo

Web頁面物件傳值Demo

最近, 論壇上很多人發如何傳值的貼子, 於是寫一個留底吧:


一、構建後臺實體類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class MainInfo
    {
        public int MainId { get; set; }
        public string MainName { get; set; }

        public List<ItemInfo> ItemList { get; set; }
    }

    public class ItemInfo
    {
        public int ItemId { get; set; }
        public DateTime AddTime { get; set; }
        public string ItemName { get; set; }

    }
}

二、前端頁面:

<script type="text/javascript">
    function save() {
        var info = {
            MainName: "Mary",
            MainId: 100
        };
        info.ItemList = [];
        info.ItemList.push({ ItemId: 1, ItemName: "m1", AddTime: "2018-11-28" });
        info.ItemList.push({ ItemId: 2, ItemName: "m2", AddTime: "2018-11-29" });

        $.ajax({
            url: "AJAX.ashx",
            data: { info: JSON.stringify(info) },
            dataType: "json",
            async: false,
            success: function (json) {
                alert(json.msg);
            }
        });

    }
</script>
<input type="button" value="Submit" onclick="save()" />

三、用一般處理程式( ashx 檔案,無aspx生命週期,效率高 , 如果 mvc 可直接用  action 方法) 來接收:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要說明
    /// </summary>
    public class AJAX : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string str = context.Request["info"];
            MainInfo info = Newtonsoft.Json.JsonConvert.DeserializeObject<MainInfo>(str);

            var r = new {
                success = info != null,
                msg = info != null ? "成功": "失敗"
            };

            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(r));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

最終, 點選後,前端頁面彈出“成功”。