knockout.js 使用knockoutjs绑定JSON对象中的数据-Asp.net MVC

dly7yett  于 2022-11-10  发布在  .NET
关注(0)|答案(1)|浏览(204)

在嵌套JSON对象的情况下,从返回的JSON中获取数据时遇到了问题。

HTML代码如下所示:

<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>

然后击倒JS

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);`

控制器:

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

Json对象:

`{"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}]}`

结果错误:

任何人都可以改善我的代码,请...

hts6caw3

hts6caw31#

您的data位于object中,因此您必须解析它:

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

如果只需要显示数据,则无需Map即可:self.Employees(myData.data);

相关问题