0

I am trying a simple binding using JsonResult from MVC Controller. The json comes back but the bindings in knockout observable array does work. Below is my code.

If I put the json result directly to the observable it works. I am not sure what I am missing here.

Knockout Code

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-min.js"></script>
<script src="~/Scripts/knockout.mapping.js"></script>

var viewModel;
vmListModel = function () {
    var self = this;

    self.Products = ko.observableArray([]);

    self.GetData = function () {
        $.ajax({
            url: '@Url.Action("product", "employees")',
            cache: false,
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            data: {},
            success: function (rs) {
                console.log(rs);  //--> the data returns like this { Id: '1001', Name: 'xavier' }
                //self.Products({ Id: '1001', Name: 'xavier' });  // if I put this it binds
                ko.mapping.fromJS(rs, {}, self.Products);
                //self.Products(ko.mapping.fromJS(rs));
            }
        });
    }


};


$(document).ready(function () {
    viewModel = new vmListModel();
    ko.applyBindings(viewModel, $('#products1')[0]);
    viewModel.GetData();
});

HTML

<table id="products1">
<thead>
    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
    </tr>
</thead>
<tbody data-bind="foreach:Products">
    <tr>
        <td data-bind="text:Id">
        </td>
        <td data-bind="text:Name">
        </td>
        <td>
        </td>
    </tr>
</tbody>

Controller code

  public JsonResult Product()
    {
        string variablename = "{Id:'1001',Name:'xavier'}";
        return Json(variablename, JsonRequestBehavior.AllowGet);
    }

Error

Uncaught ReferenceError: Unable to process binding "text: function (){return Id }" Message: Id is not defined

12
  • Can you make the changes as per your data bind logic jsfiddle.net/zNkhR/138 ? I have made a basic setup which works. Commented Jul 25, 2015 at 9:43
  • Not sure what you mean, but this data come from the controller. Is there something I need to on the controller? Commented Jul 25, 2015 at 9:57
  • from the comments i just copied the structure to a variable and initialized the view model. Verify what you are getting the same structure from the action method. Commented Jul 25, 2015 at 10:00
  • in the console.log I am getting this {Id:'1001',Name:'xavier'} and if I check in the observable I am getting this viewModel.Products() "{Id:'1001',Name:'xavier'}" Commented Jul 25, 2015 at 10:04
  • 1
    Try ko.mapping.fromJS(JSON.parse(rs), {}, self.Products);. You get back string from the ajax call, you need to convert it to object before you can call fomJS with it. Commented Jul 25, 2015 at 10:25

1 Answer 1

3

Your are passing data of type string from controller and trying to convert using mapping plugin which is wrong in all sorts

FIX: Build a array and pass it . so mapping plugin will convert everything to observable's and you can have successful 2-way binding intact .

Controller :

var data = new[] { new { Id = "1001", Name = "Nancy" }, new { Id = "1002", Name = "bunny" } };
return Json(data, JsonRequestBehavior.AllowGet);

Hope that helps

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

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.