将JSON传递给MVC 3 Action

Eil*_*int 8 asp.net asp.net-mvc json controller asp.net-mvc-3

我正在尝试将JSON提交给MVC操作.我想要的是获取JSON对象,然后访问它的数据.JSON字段的数量每次都会有所不同,所以我需要一个能够处理所有情况的解决方案.

这是我对我的行动的POST,地址可以有3个字段或20个,每个帖子都会有所不同.

更新:我会详细介绍一下.我正在尝试使用LinkedIn API,我将收到一个JSON,它看起来像本页末尾的JSON:link.我需要创建一个接受这个JSON的Action,它会因人而异.

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");
        }
    });
Run Code Online (Sandbox Code Playgroud)

这是我在MVC中的操作,我需要应用于传递任何JSON对象并访问其字段.

 [HttpPost]
    public ActionResult GetDetails(object address)
    {         
        //address object comes in as null            

        @ViewBag.Successs = true;

        return View();

    }
Run Code Online (Sandbox Code Playgroud)

Tae*_*hin 5

我不相信没有人这样说,所以我会尝试.让你的代码像这样

 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();

}
Run Code Online (Sandbox Code Playgroud)

通常,您可以将这些可能的属性添加到Personal类(或任何您可以命名的类)中.但根据linkedin API,由于其复杂性,您将需要一个生成数据类的工具.我认为xsd.exe可以帮助你,如果你可以得到xsd文件(或者你甚至可以从xml生成xsd文件)