Corner friendly inverse List and Dictionary types with ServiceStack

AngularJS cannot bind to a value type model, as described here:

On the server side, I only have a list of lines:

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

When I want to bind ( from ng-model to inputs ) to list items via ng-repeat, this will not work because ServiceStack serializes them as an array of strings.

Can you tell the ServiceStack serializer to serialize and deserialize lists and dictionaries as objects that can be used with AngularJS bindings?

eg.

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

The same goes for dictionaries.

The only solution I found was to return List<KeyValuePair<string, string>> , but it is very ugly on the server side.

+4
source share
1 answer

Why do you need to convert a list of strings to an associative array? AngularJs can handle iteration over an array.

Here's a plnkr that demonstrates: http://plnkr.co/edit/TcXxSBkt7NBkqNJhkSE1

essentially, the server returns an object, and the SomeListItems property is an array.

use ng-repeat to iterate over them

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

I see a couple of solutions to this problem, either by massaging the data structure on the client or on the server.

Here is plnkr , which shows the conversion of an array of strings received from the server into an associative array, so it can be edited on the client, and then re-converted back to one dimensional array for publication on the server.

Conversely, you can do this on the server. If you declare SomeListItems as a dynamic list, then you can assign everything you want, including anonymous objects that the ServiceStack serializer should handle (I have not tested this, but I think it will work).

 [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 

alternatively, you can specify a custom class that is less verbose than KeyValuePair<string, string>

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

and then redefine the model

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

this is a little more verbose than using dynamics, but JSON serialization should definitely handle this.

+4
source

Source: https://habr.com/ru/post/1480770/


All Articles