如何从客户端向服务器端发送复杂类型

时间:2016-06-29 10:20:42

标签: json ajax asp.net-mvc

我有一个页面需要将复杂数据从客户端发送到asp.net mvc中的webmethod。 我的数据是:

    {"tbl":[{"row":{"items":[{"name":"madrak1","val":"fdsfds"},{"name":"mahaleTahsil1","val":"fdsfds"},{"name":"reshte1","val":""},{"name":"start1","val":""},{"name":"end1","val":""}]}}]}

我需要一个名为table的类,它将所有变量放在其中。 我的网络方法是:

 public ActionResult SaveDetailedInfo(List<rrow> tbl)
    {
        return Json(new { status = "Success", message = "Success" });
    }

1 个答案:

答案 0 :(得分:0)

您的C#类应该类似于:

public class Item
{

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("val")]
    public string Val { get; set; }
}

public class Row
{

    [JsonProperty("items")]
    public IList<Item> Items { get; set; }
}

public class Tbl
{

    [JsonProperty("row")]
    public Row Row { get; set; }
}

public class Table
{

    [JsonProperty("tbl")]
    public IList<Tbl> Tbl { get; set; }
}

你的MVC方法:

public ActionResult SaveDetailedInfo(Table table)
{
    return Json(new { status = "Success", message = "Success" });
}

所以从前端发送数据......

var table = {
    "tbl": [{
        "row": {
            "items": [{
                "name": "madrak1",
                "val": "fdsfds"
            }, {
                "name": "mahaleTahsil1",
                "val": "fdsfds"
            }, {
                "name": "reshte1",
                "val": ""
            }, {
                "name": "start1",
                "val": ""
            }, {
                "name": "end1",
                "val": ""
            }]
        }
    }]
};

var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/SaveDetailedInfo', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

// send the collected data as JSON
xhr.send(JSON.stringify(table));

应该导致......

enter image description here

PS。 There is an easy way to convert your json objects into C# classes