来自Controller的JSON格式数据不绑定到Grid

时间:2014-04-08 07:41:47

标签: jquery json asp.net-mvc-4 knockout.js jqgrid

我有一个控制器,它以 JSONResult 格式返回对象列表。在我看来,我已经编写了 $ .ajax 方法来从控制器获取数据。我使用 Knockout JS 进行数据绑定到我的网格。当我对值进行硬编码时,数据绑定到网格(下面的代码块被注释)。但是当我从ajax调用传递数据时,它没有绑定。有人可以帮我解决这个问题吗?

控制器代码:

[HttpGet]
public ActionResult FetchMyData()
{
    List<SomeData> myData = new List<SomeData>();
    MyViewModel model = new MyViewModel();
    model.myData = new List<SomeData>();

    model.myData.Add(new SomeData() { Id = 1, Record = "Record 1", RecType = "Type 1" });
    model.myData.Add(new SomeData() { Id = 2, Record = "Record 2", RecType = "Type 2" });
    model.myData.Add(new SomeData() { Id = 3, Record = "Record 3", RecType = "Type 3" });
    model.myData.Add(new SomeData() { Id = 4, Record = "Record 4", RecType = "Type 4" });
    model.myData.Add(new SomeData() { Id = 5, Record = "Record 5", RecType = "Type 5" });
    JsonResult outputResult = Json(model.myData, JsonRequestBehavior.AllowGet);
    return outputResult;
}

ViewModel代码:

public class MyViewModel
{
    public List<SomeData> myData;
}

public class SomeData
{
    public int Id;
    public string Record;
    public string RecType;
}

观看代码:

<div data-bind="jqGrid:grid"></div>

<script type="text/javascript">
var jsonData;
$(document).ready(function () {
    $.ajax({
        type: "Get",
        url: '@Url.Action("FetchMyData", "Grid")',
        dataType: "json",
        async: false,
        success: function (Data) {
            jsonData = Data;
        }
    });

    var model = function () {
        var self = this;
        self.items = ko.observableArray(jsonData);

        //self.items = ko.observableArray([
        //    { "Id": 1, Record: "Record 1", Record Type: "Type 1" },
        //    { "Id": 2, Record: "Record 2", Record Type: "Type 2" },
        //    { "Id": 3, Record: "Record 3", Record Type: "Type 3" }
        //]);

        self.grid = new ko.jqGrid({
            dataSource: self.items,
            columns: [
                { type: "index", dataField: "Id" },
                { headerText: "Id", dataField: "Id" },
                { headerText: "Record", dataField: "Record" },
                { headerText: "Record Type", dataField: "Record Type" }
            ],
            allowSorting: true,
        });
    };
    var myModel = new model();
    ko.applyBindings(myModel);
});
</script>

1 个答案:

答案 0 :(得分:1)

用这个替换你的成功函数:

success: function (Data) {
    jsonData = Data;
    myModel.items(jsonData);
}