0

I have a problem to get data from returning JSON in case of nested JSON objects.

HTML code looks like:

<div>
    <h2>List Employee</h2>
    <br />
    <table class="table table-bordered" >
        <thead>
            <tr>
                <td>Id</td>
                <td>Name</td>
                <td>Age</td>
            </tr>
        </thead>
        <tbody data-bind="foreach: Employees">
            <tr>
                <td data-bind="text: Id"></td>
                <td data-bind="text: Name"></td>
                <td data-bind="text: Age"></td>
            </tr>
        </tbody>
    </table>
</div>

then KnockoutJS

function ProductViewModel() {
    var self = this;
    self.Employees = ko.observableArray();`

    $.ajax({
        url: '/Home/GetEmployee',
        cache: false,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        data: {},
        success: function (data) {
            self.Employees(ko.mapping.fromJS(data));
        }
    })
} 
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);`

Controller:

public JsonResult GetEmployee()
{
    var employee = db.Employee.ToList();
    return Json(new { data = employee }, JsonRequestBehavior.AllowGet);
}

Json Object:

`{"data":[{"Id":1,"Name":"Andrew","Age":25},{"Id":2,"Name":"John","Age":28},{"Id":3,"Name":"Layla","Age":24},{"Id":4,"Name":"Mia","Age":26}]}`

Result Error:

Result Error

Anybody can improve my Code, please...

1
  • @Phong, thanks for edited. Commented Jan 20, 2020 at 3:18

1 Answer 1

0

Your data is in object so you have to parse it:

const myData = JSON.parse(data);
self.Employees(ko.mapping.fromJS(myData.data)); //in data is your array

If you need data only for display you can do it without mapping: self.Employees(myData.data);

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.