Adrian
Adrian

Reputation: 333

MVC Controller returning JSON but not binding in Knockout

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

Upvotes: 0

Views: 476

Answers (1)

super cool
super cool

Reputation: 6045

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

Upvotes: 3

Related Questions