2013-05-14 70 views
4

AngularJS不能绑定到一个值类型的模型,如下解释:AngularJS友好的返回类型列表和字典的与ServiceStack

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

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

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

Whe n我想通过ng重复绑定(与ng-model输入)到列表项中,因为ServiceStack将它们序列化为字符串数组,所以它不起作用。

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

E.g.

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

相同的字典。

我发现的唯一解决方案是返回一个List<KeyValuePair<string, string>>,但在服务器端非常难看。

回答

4

为什么你需要将字符串列表转换为关联数组? 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序列化应该能够处理这个问题。

+0

Thans为您的答案。是的单向绑定工作正常,但我想绑定与ng模型输入。对不起,如果这在我的问题中不明确。 – dna 2013-05-15 05:07:04

+1

我更新了我的答案 – Jason 2013-05-15 15:36:29

+0

非常感谢。 – dna 2013-05-15 16:48:44