gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:21:09 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com