c# - 带有 ServiceStack 的 List 和 Dictionary 的 AngularJS 友好返回类型

标签 c# json rest angularjs servicestack

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

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

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

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

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

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

例如

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

字典也一样。

我找到的唯一解决方案是返回 List<KeyValuePair<string, string>>但这在服务器端非常丑陋。

最佳答案

为什么要把字符串列表转成关联数组? 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<string, string> 更简洁的自定义类

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 序列化应该绝对能够处理这个问题。

关于c# - 带有 ServiceStack 的 List 和 Dictionary 的 AngularJS 友好返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549312/

相关文章:

java - 具有多个同名参数的 JAX-RS 查询

rest - 使用 Apache Camel 的微服务

c# - 使用 XMLReader 在 c# 中为多个相似节点解析 XML

c# - Console.ReadLine 和 Console.In.ReadLine 之间的区别

c# - 银光端口

web-services - 具有关联资源的 REST 服务的正确 URI 设计是什么

c# - NServiceBus 处理程序抛出元数据错误

java - JSONProvider 返回空对象,例如 String

javascript - 如何从 json 字符串中递归获取父 ID

javascript - 在 Meteor 中解析错误的服务器响应