Asp.net
將 JSON 傳遞給 MVC 3 操作
我正在嘗試將 JSON 送出給 MVC 操作。我想要的是獲取 JSON 對象,然後訪問它的數據。JSON 欄位的數量每次都會有所不同,因此我需要一個可以處理所有情況的解決方案。
這是我的文章,地址可能有 3 個欄位或 20 個欄位,每個文章都會有所不同。
更新:我會更詳細一點。我正在嘗試使用 LinkedIn API,我將收到一個類似於本頁末尾的 JSON 的 JSON:連結。我需要創建一個 Action 來接受這個因人而異的 JSON。
var address = { Address: "123 rd", City: "Far Away", State: "Over There" }; $.ajaxSetup({ cache: false }); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/Account/GetDetails/", data: JSON.stringify(address), dataType: "json", success: function () { alert("Success from JS"); } });這是我在 MVC 中的操作,我需要申請獲取傳遞的任何 JSON 對象並訪問其欄位。
[HttpPost] public ActionResult GetDetails(object address) { //address object comes in as null @ViewBag.Successs = true; return View(); }
我不相信沒有人這麼說,所以我會嘗試。有這樣的程式碼
public class Personal { public string Address { get; set; } public string City { get; set; } public string State { get; set; } //other properties here } [HttpPost] public ActionResult GetDetails(Personal address) { //Should be able to get it. @ViewBag.Successs = true; return View(); }通常,您可以將這些可能的屬性添加到 Personal 類(或您可以命名的任何名稱)中。但是根據linkedin API,由於其複雜性,您將需要一個工具來生成數據類。如果您可以為此獲取 xsd 文件,我認為 xsd.exe 可以提供幫助(或者您甚至可以從 xml 生成 xsd 文件)