绑定MVC中的对象数组

时间:2013-12-03 06:06:16

标签: c# asp.net-mvc json asp.net-mvc-5

我在MVC5中绑定一组键值对象时遇到问题。这是JSON:

{
    "expiration": "2013-12-03T04:30:41.206Z",
    "conditions": [
        {
            "acl": "private"
        },
        {
            "bucket": "ryvus.upload.test"
        },
        {
            "Content-Type": "application/vnd.ms-excel"
        },
        {
            "success_action_status": "200"
        },
        {
            "key": "fc42ae8a-1f6e-4955-a669-8272ad650cb9.csv"
        },
        {
            "x-amz-meta-qqfilename": "simpleupload.csv"
        }
    ]
}

如果我尝试将条件绑定到这样的Dictionary<string, string>

// View Model
public class ResponseVM
{
    public DateTime Expiration { get; set; }
    public Dictionary<string, string> Conditions { get; set; }
}
// Controller Action
public ActionResult MyHandler(ResponseVM s3Response)
{
   //do something
   return JSON(null);
}

我得到6个条目,其键为“0”,“1”,“2”,“3”,“4”,“5”和空值。我似乎非常接近,但我尝试了一堆不同的类型而没有成功,Dictionary<string, string>是我能得到的最好的。

我错过了一些完全明显的东西吗?

3 个答案:

答案 0 :(得分:1)

由于无法更改JSON方案,最简单的方法是更改​​类以匹配JSON。

public class ResponseVM
{
    public DateTime Expiration { get; set; }
    public List<Dictionary<string, string>> Conditions { get; set; }
}

条件是地图列表。

顺便说一下,视图模型(VM)的目的是抽象视图。这不是输入。

答案 1 :(得分:0)

$.ajax({
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify(data),
    url: "your url",
    contentType: 'application/json; charset=utf-8',
    success: function (t) {
        // code here
    }
});

试试吧。

我没有绑定到字典,但数组工作正常。

答案 2 :(得分:0)

我认为问题在于conditions结构无法映射到键值对...... conditions结构实际上是 一组不同类型的对象,例如第一个对象可以建模:

    public class ACL {
        public string acl { get; set; }
    }

下一个对象如:

    public class Bucket {
        public string bucket { get; set; }
    }

等。它不是可绑定的键值对。

要使条件结构绑定到KeyValuePair<TKey, TValue>结构,您希望JSON看起来更像这样:

    {
        "expiration": "2013-12-03T04:30:41.206Z",
        "conditions": [
            {
                Key: "acl",
                Value: "private"
            },
            {
                Key: "bucket",
                Value: "ryvus.upload.test"
            },
            ...
        ]
    }

编辑:如果你不能改变JSON模式并且你不打算编写自定义绑定器那么下面的结构应该可以工作,但它是 不漂亮,因为NVPair中的每个项目都有conditions的实例。

你的模特:

    public class NVPair {
        public string acl { get; set; }
        public string bucket { get; set; }
        [JsonProperty("Content-Type")]
        public string ContentType { get; set; }
        public string success_action_status { get; set; }
        public string key { get; set; }
        ...
    }

    public class ResponseVM
    {
        public DateTime Expiration { get; set; }
        public List<NVPair> Conditions { get; set; }
    }

这样每个nvp都会有一个单独的项目。但它应该绑定。

如果您不想要JSON.Net的JsonProperty attrib,您可以DataContract使用{{1}}

相关问题