2

I started using knockout in my asp.net mvc 2 project

anyway i tried something simple. i created a model like so:

var userViewModel = {
ID: ko.observable(),
assignedGroups: ko.observableArray(),
avilableGroups: ko.observableArray(),
permissions: ko.observableArray()
};

then on the document.ready of jquery i called:

ko.applyBindings(userViewModel);

in the aspx itself i have:

<select multiple id="groupOfUser" class="multi_added_groups" data-bind="foreach:    assignedGroups">
  <option data-bind="text: $data, value: $data"></option>
</select> 
<span data-bind="text: ID"></span>

if i first put data into userViewModel the view displays as expected. and that's great but i want the view to start off empty at first. then after the user chooses a user i make an ajax request my response is this:

{"ID":691,
"assignedGroups":["group1","group2"],
"avilableGroups":["role.administrator","role.editor"],
"permissions":[{"name":"admin","level":"ReadWrite"},
{"name":"admin.errorInfo","level":"Read"}]
 }

then in my callback function:

ko.mapping.fromJS(res, userViewModel);

and that's it i guess. my view doesn't get refreshed with the new data from the server... what am i doing wrong?

thanks!

4

1 回答 1

4

I've run into this issue myself a couple of times. It seems that the mapping plugin expects your object to have been initially created from mapped data. This is a bit of a limitation of the plugin but can easily be worked around. Here is an example of creating your properties with the plugin where the update works correctly.

http://jsfiddle.net/madcapnmckay/8BVMZ/1/

var userViewModel = function () {
    var self = this;
    ko.mapping.fromJS({
        ID: "",
        assignedGroups: [],
        avilableGroups: [],
        permissions: []            
    }, {}, self);

    userSelected = function () {
        ko.mapping.fromJS(ajaxResponse, {}, self);
        console.log(JSON.stringify(ko.toJS(self)));
    }
};

Hope this helps.

于 2012-05-24T15:49:11.457 回答