0
votes

Im stuck with another MVC/Knockout issue..

This time it is related with a serialization/dictionary collection.

I have the following view model

public class ListViewModel
{
    public Dictionary<ItemViewModel, List<ItemViewModel>> Events { get; set; }

    public ListViewModel()
    {
        Events = new Dictionary<ItemViewModel, List<ItemViewModel>>();
    }
}

public class ItemViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and the cshtml file:

<h2>Events</h2>
<div data-bind="template: { name: 'events-template', foreach: Events }"></div>

<script type="text/html" id="events-template">
    <ul>
        <li>
            <div><span data-bind='text: Events().length'/></div>
            <ul data-bind="foreach: Events">
                <li><span data-bind="text: $data"> </span></li>
            </ul>
        </li>
    </ul>     
</script>

<script type="text/javascript">

    var ListViewModel = function(model) {
        var self = this;

        self.Events = ko.observableArray(ko.utils.arrayMap(model.Events, function(itemViewModel) {
            var item = new ItemViewModel(itemViewModel);
            return item;
        }));
    };

    var ItemViewModel = function(itemViewModel) {
        var self = this;
        self.Name = ko.observable(itemViewModel.name);
        self.Id = ko.observable(itemViewModel.Id);
    };

    $(function() {
        var data = @(Html.Raw(Json.Encode(Model)));        
        ko.applyBindings(new ListViewModel(data));
    });

</script>

it seems to be getting stuck on var data = @(Html.Raw(Json.Encode(Model)));

the error message mentions something like "Type Generic Dictionary... is not supported for serialization/deserialization of a dictionary, keys must be strings or objects."

1

1 Answers

0
votes

As exception says - .NET doesn't support serialization of dictionaries. You have to consider 3 options:

  • If possible replace dictionary with any serializable data structure.
  • Write json serializable dictionary or find existing one.
  • Write javaScriptSerializer that will serialize dictionary.