从json字符串构建jqgrid中的下拉列表

时间:2016-05-11 18:43:16

标签: json jqgrid

在我的编辑表单中,我想填充服务器的下拉列表。我成功地将json字符串中的值返回给客户端:

var types = 
    $.ajax({
        url: getTypesUrl,
        async: false,
        success: function (data, result) {
            if (!result)
                alert("failed to retreive harvest types.");
        }
}).responseText;

返回此字符串:

 [{"HarvestTypeId":1,"TypeDescription":"Elite Gain / High Elev"},{"HarvestTypeId":2,"TypeDescription":"High Gain / High Elev"},{"HarvestTypeId":3,"TypeDescription":"Med Gain / High Elev"}]

然后我使用loadComplete:

将它添加到我的jqgrid
$("#harvest-grid").jqGrid({
    url: gridUrl,
    styleUI: "Bootstrap",
    datatype: 'json',
    colNames: ['HarvestId', 'Harvest Year', 'Harvest Type'],
    colModel: [
            { name: "HarvestId", key: true, hidden: true },
            { name: "HarvestYear", search: true, editable: true },
            { name: "HarvestType", search: true, editable: true, edittype: "select" }
    ],
    loadonce: true,
    height: "auto",
    autowidth: true,
    rowNum: -1,
    pager: "#harvest-pager",
    editurl: editHarvestUrl,
    loadComplete: function () {
        $("#harvest-grid").setColProp('HarvestType', { editoptions: { value: types } });
    }
});

编辑表单显示一个选择列表框,但将整个json字符串呈现为唯一选项而不是构建列表:

<select role="select" id="HarvestType" name="HarvestType" rowid="4430" size="1" class="FormElement form-control">
    <option role="option" value="[{&quot;HarvestTypeId&quot;">1,"TypeDescription":"Elite Gain / High Elev"},{"HarvestTypeId":2,"TypeDescription":"High Gain / High Elev"},{"HarvestTypeId":3,"TypeDescription":"Med Gain / High Elev"}]</option>
</select>

1 个答案:

答案 0 :(得分:1)

我建议您使用editoptionsdataUrl: getTypesUrl属性使用异步加载数据。您还应该另外指定buildSelect回调,它将从getTypesUrl返回的数据转换为字符串

<select>
    <option value='1'>Elite Gain / High Elev</option>
    <option value='2'>High Gain / High Elev</option>
    <option value='3'>Med Gain / High Elev</option>
</select>

如果您在{{返回的数据中使用命名属性(如prmNames: { id: "HarvestId" }),我建议您另外添加"HarvestId"选项并删除隐藏列{"HarvestId": 123, "HarvestYear": 2016, "HarvestType": "Med Gain / High Elev"} 1}}。