0
votes

here i got a sample code which said KnockoutJS Mapping plugin automatically bind UI. here is code

<script src="~/Scripts/knockout.mapping-latest.js"></script>
 <script type="text/javascript">
        $(function() {
            var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson()));
            ko.applyBindings(viewModel);
          });
</script> 

suppose my html binding as follows

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

and my server side model return json like

{fname:Josh;lname:Steve};

so here my question is how KnockoutJS Mapping plugin could understand that fname value need to map to databinding firstName & lname need to map to databinding lastName ?

am i clear what i am trying to say. so guide me in this case how one could bind json to html UI through KnockoutJS Mapping plugin.

in this situation KnockoutJS Mapping plugin would be right choice or not ?

do i need to bind manually by viewmode like

First name:

Last name:

json as follows var person = {fname:Josh;lname:Steve};

var viewModel = function(person) {
    this.firstname= ko.observable(person.fname);
    this.lastname= ko.observable(person.lname);
};

ko.applyBindings(new viewModel(person));
1
If you want to use different properties names in your views like lastname what you have on the server fname then the mapping plugin cannot really help you. You need to manually do the mapping as in your second example. - nemesv
thanks...so when mapping plugin will use then server side viewmode & client side viewmodel has to be same....am i right? - Thomas
mapping plugin creates the viewModel with properties with same names as the model it gets; if you have only some properties, that you want to have different names, you can extend the viewModel after mapping - Matus
thanks @Matus but this is not clear to me what u have said "you can extend the viewModel after mapping" can u please explain bit more about your statement. thanks - Thomas

1 Answers

0
votes

As requested in the comment I put this as a possible answer.

If you have model with many properties and want only some of them to map to different names, this is the way to do it:

var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson()));
var extendViewModel = function () {
    this.firstName = ko.computed({
        read: function(){
            return viewModel.fname();
        },
        write: function(value){
            viewModel.fname(value);
        },
        owner: viewModel
    });
};

viewModel = ko.mapping.fromJS(new extendViewModel(), viewModel);
ko.applyBindings(viewModel);

Then you can use firstName in your markup for bindings and viewModel.fname will be updated, too.