後端與多層次 json 資料傳入與送出 - 使用 Json.NET
本文章只列範例不說明
一、準備一範例,檔案結構如下圖

二、Model
在 Models 部份,有三個檔案,其內容分別為
QueryModel.cs
using System.Collections.Generic;
namespace WebApplication1.Models
{
public class QueryModel
{
public Header header { get; set; }
public IEnumerable<Detail> details { get; set; }
public long[] deleteList { get; set; }
}
}
Header.cs
namespace WebApplication1.Models
{
public class Header
{
public int id { get; set; }
public string name { get; set; }
}
}
Detail.cs
namespace WebApplication1.Models
{
public class Detail
{
public int no { get; set; }
public string productName { get; set; }
public int quantity { get; set; }
public int price { get; set; }
}
}
三、Controller
HomeController.cs
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult GetJson(QueryModel obj)
{
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(obj), "application/json", System.Text.Encoding.UTF8);
}
}
}
四、View
Index.cshtml
@{
ViewBag.Title = "Home Page";
}
@section scripts{
<script>
var objectH = { id: 1, name: "Tom" };
var objectDs = [
{ no: 1, productName: "hat", quantity: 2, price: 100 },
{ no: 2, productName: "shoes", quantity: 1, price: 500 }
];
var delList = [111, 222, 333];
var MyJson = JSON.stringify({ header: objectH, details: objectDs, deleteList: delList });
$(document).ready(function () {
$.ajax({
url: "GetJson",
type: "post",
dataType: "json",
data: MyJson,
contentType: 'application/json; charset=utf-8',
success: record
});
});
function record(data) {
console.log(data.header.name + " is buyer");
}
</script>
}
五、執行結果
