2

I am trying to convert my mvc model to knockout viewmodel here:

Model

public class MyModel
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    .
    .
    .
    public List<MyList1> MyListOne{ get; set; }
    public List<MyList2> MyListTwo{ get; set; }  
}

Controller

public ActionResult Index()
{
      MyModel myModel;

      var myServiceObject = myServiceManager.GetMyModelByUser(user);

      myModel = new MyModel
      {
        Id = myServiceObject.Id,
        .
        . 
        .
        .
      };

      return View(myModel);  
}

View Model

var DynamicModelLoading = function (data) {
    var self = this;

    ko.mapping.fromJS(data, {}, self);

};

Helper

public static string ToJson(this object obj)
        {
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            return JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings);
        }

View

<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/knockout-3.2.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">
    var viewModel;

    $(function () {
            var viewModel = new DynamicModelLoading(@Html.Raw(Model.ToJson()));            
            ko.applyBindings(viewModel);
   });
</script>

<div class="f_name" data-bind="text: FirstName"></div>
<div class="f_name" data-bind="text: LastName"></div>

ToJson() returns data. But while binding it I am not getting any error and no data either. I am missing something here but not sure what it is.


Answer

Here is the fix:

<div class="f_name" data-bind="text: firstName"></div>
<div class="f_name" data-bind="text: lastName"></div>

I was expecting the property name as same as my mvc model, but Json Serializer converts capitalized first letter to lower case by default.

1

2 Answers 2

1

The issue must have something to do with the JSON result coming from @Html.Raw(Model.ToJson()));

Just to play around with the code a little, I created this fiddle which seems to be mapping the data correctly, and successfully binding it to the view: http://jsfiddle.net/4Lu8fdx2/

Here is the JavaScript code:

var DynamicModelLoading = function (data) {
    var self = this;

    ko.mapping.fromJS(data, {}, self);
};

$(function () {
    var viewModel = new DynamicModelLoading({"testProperty":"testValue"});

    ko.applyBindings(viewModel);
});

This successfully binds the static JSON being passed in to "DynamicModelLoading()" to the HTML in the view. Here is the HTML:

<h4>Value For 'testProperty'</h4>
<span data-bind="text: testProperty"></span>

What happens when you log your viewModel to the console, just before calling 'applyBindings()'? Does it contain all of the properties from your original JSON object configured as observables (functions)? When I log the viewModel, this is what I get:

DynamicModelLoading {testProperty: function, __ko_mapping__: Object}

If the mapping is working successfully, you should get a similar result, but with all the properties from your object.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, hope it helped!
0
var viewModel; $(function () { var viewModel = new DynamicModelLoading(JSON.parse('@Html.Raw(Json.Encode(Model))')); ko.applyBindings(viewModel); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.