【问题标题】:AngularJS friendly return types of List and Dictionary with ServiceStack使用 ServiceStack 的 AngularJS 友好返回类型的 List 和 Dictionary
【发布时间】:2013-05-14 17:29:44
【问题描述】:

AngularJS 无法绑定到值类型模型,如下所述:

在服务器端,我只有一个字符串列表:

[Route("/path/{Id}", "GET, OPTIONS")]
public class MyModel
{
    public int Id { get; set; }

    public List<string> SomeListItems { get; set; }
}

当我想通过 ng-repeat 将(使用 ng-model 到输入)绑定到列表项时,它不起作用,因为 ServiceStack 将它们序列化为字符串数组。

是否可以告诉 ServiceStack 序列化程序序列化和反序列化列表和字典作为可与 AngularJS 绑定一起使用的对象?

例如

{
    "id": 1,
    "someListItems": [
        { "value": "Item1" },
        { "value": "Item2" },
        ...
    ]
}

字典也是如此。

我找到的唯一解决方案是返回 List&lt;KeyValuePair&lt;string, string&gt;&gt;,但这在服务器端非常难看。

【问题讨论】:

    标签: c# json rest angularjs servicestack


    【解决方案1】:

    为什么需要将字符串列表转换为关联数组? AngularJs 可以处理对数组的迭代。

    这是一个 plnkr 演示:http://plnkr.co/edit/TcXxSBkt7NBkqNJhkSE1

    本质上,服务器返回对象,属性 SomeListItems 是一个数组。

    使用ng-repeat 迭代它们

    <ul>
        <li ng-repeat="item in data.SomeListItems">{{item}}</li>
      </ul>
    

    我看到了一些解决这个问题的方法,可以在客户端或服务器上调整数据结构。

    Here's a plnkr 显示将从服务器接收到的字符串数组转换为关联数组,以便可以在客户端对其进行编辑,然后重新转换回单维数组以发布到服务器。

    相反,您可以在服务器上执行此操作。如果您将 SomeListItems 声明为动态列表,那么您可以为其分配任何您想要的东西,包括 ServiceStack 序列化程序应该能够处理的匿名对象(我还没有测试过,但我认为它会起作用)。

    [Route("/path/{Id}", "GET, OPTIONS")]
    public class MyModel
    {
        public int Id { get; set; }
    
        public List<dynamic> SomeListItems { get; set; }
    }
    
    // in a controller or service
    var model = new MyModel() { Id = 1 };
    model.SomeListItems =  new List<dynamic> {
      new { Key = 1, Value = "foo }, new {Key = 2, Value = "bar" }
    }; // this should serialize to JSON as { Id: 1, SomeListItems: [ {Key: 1, Value: 'foo'}, {Key:2, Value = 'bar'}]}; which angular can handle nicely
    

    或者,您可以指定一个比KeyValuePair&lt;string, string&gt; 更简洁的自定义类

    public class JsonPayload
    { // yes, it's just a KVP, but it's much more concise
      public string Key {get;set;}
      public string Value {get;set;}
    }
    

    然后重新定义你的模型

    [Route("/path/{Id}", "GET, OPTIONS")]
    public class MyModel
    {
        public int Id { get; set; }
    
        public List<JsonPayload> SomeListItems { get; set; }
    }
    

    这比使用动态更冗长,但 JSON 序列化肯定能够处理。

    【讨论】:

    • 感谢您的回答。是的,单向绑定效果很好,但我想用 ng-model 绑定到输入。抱歉,如果我的问题不清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2019-12-03
    • 2013-04-27
    • 2013-05-15
    相关资源
    最近更新 更多