复杂匿名对象的 ViewModel 替换

ViewModel replacement for complex Anonymous Object

所以我正在处理这个复杂的匿名对象

        var result = new 
            {    
                percentage = "hide",
                bullets = (string)null,
                item = new [] {
                    new {
                        value = 16,
                        text = "Day",
                        prefix = (string)null,
                        label = (string)null
                    },
                    new {
                        value = 41,
                        text = "Week",
                        prefix = (string)null,
                        label = (string)null
                    },
                    new {
                        value = 366,
                        text = "Month",
                        prefix = (string)null,
                        label = (string)null
                    }
                }
            };

我想将它转换成一个 ViewModel 并 return 它作为 JSON 从休息 API。

我想知道的是

  1. 如何将其表示为包含数组项条目的模型
  2. 创建模型实例后如何将数组项添加到数组
  3. 模型是否需要构造函数来初始化数组。

如果您能提供任何帮助或示例,那就太好了。

创建一个 class 结构:

public class Result
{
    public Result()
    { 
        // initialize collection
        Items = new List<Item>();
    }

    public string Percentage { get; set; }
    public string Bullets { get; set; }
    public IList<Item> Items  { get; set; }

}

public class Item
{
   public int Value { get; set; }
   public string Text { get; set; }
   public string Prefix { get; set; }
   public string Label { get; set; }
}

然后将您的代码更改为:

var result = new Result
            {    
                Percentage = "hide",
                Bullets = (string)null,
                Items = {
                    new Item {
                        Value = 16,
                        Text = "Day",
                        Prefix = (string)null,
                        Label = (string)null
                    },
                    new Item {
                        Value = 41,
                        Text = "Week",
                        Prefix = (string)null,
                        Label = (string)null
                    },
                    new Item {
                        Value = 366,
                        Text = "Month",
                        Prefix = (string)null,
                        Label = (string)null
                    }
                }
            };  
  1. 上面用结构寻址。
  2. 添加到collection如下:

    result.Items.Add(new Item { Value = 367, Text = "Month", Prefix = (string)null, Label = (string)null });

  3. 我会在上面的构造函数中初始化 collection。

向控制器操作中的 return json 添加以下内容:

return Json(result, JsonRequestBehavior.AllowGet);