我想在 jqgrid 的 DropDown 中加载服务器数据。我的代码,
更新的代码:
public ActionResult GetUnit()
{
List<UnitModel> getUnitValues = new List<UnitModel>();
//ToDo db code
Dictionary<int, string> unitValues = new Dictionary<int, string>();
unitValues = getUnitValues.ToDictionary(x => x.UnitID, x => x.UnitDesc);
unitValues.Add(4, "Unit2/3");
unitValues.Add(1, "Unit1");
unitValues.Add(2, "Unit2");
unitValues.Add(3, "Unit3");
return Json(unitValues, JsonRequestBehavior.AllowGet);
}
我的jqgrid:
colModel: [...
{
name: 'UnitID', index: 'UnitID', editable: true, edittype: 'select', width: "200",
formatter: 'select', editoptions: { value: unitslist},
editrules: { custom: true, custom_func: dupicateRecordValidation
}
},
...],
beforeProcessing: function () {
$.ajax({
url: '/Home/GetUnit/',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$.map(data, function (value, key) {
unitsList += '"' + value + '"' + ':' + '"' + key + '"' + ',';
});
unitsList += '}';
alert(unitsList);
}
});
},
但是,这不起作用。 jqgrid DropDown 列加载了空单元格。我错过了什么吗?这是正确的方法吗?请建议是否有其他方法可以使用服务器数据加载 jqgrid 的下拉列表,并选择该行的默认值。谢谢。
注意:我使用的是 Jquery jqgrid v4.4.4 Visual Studio
最佳答案
首先,了解何时应该使用 formatter: 'select'
很重要,您当前使用的。如果你想用UnitID
中的id信息填充网格,则这是必需的,但您需要显示与 id 相对应的文本。例如,您从服务器获取的 JSON 数据可能包含属性 language
,内容为"de"
, "en"
, "fr"
等等,但你想显示在"German"
列中而不是"de"
, "English"
而不是"en"
和"French"
而不是"fr"
。在这种情况下你应该定义
formatter: 'select', editoptions: { value: 'de:German;en:English;fr:French' },
editable: true, edittype: 'select'
如果您确实需要使用formatter: 'select'
,并且您需要加载 editoptions.value
通过来自服务器的 Ajax,然后 editoptions.value
必须在从url
返回的网格的主要数据之前设置。将被处理。在这种情况下,我建议您扩展从url
返回的标准数据。以及 editoptions.value
所需的数据。可以使用beforeProcessing
回调(即使在您使用的复古版本 4.4.4 中也支持)并设置 editoptions.value
动态地考虑setColProp
方法。请参阅the answer了解更多详细信息和代码示例。
如果您不需要使用formatter: 'select'
(如果 select 中使用的 ids 和值相同),那么您可以更改从 GetUnit
返回的数据格式对序列化数组的操作:
["Unit1", "Unit2", "Unit2/3"]
并使用dataUrl
与 buildSelect
editoptions
的属性而不是value
。 dataUrl
的值网址应为GetUnit
操作,返回包含所有 utits 的字符串数组。回调buildSelect
应该将 JSON 数组转换为 HTML 片段,表示 <select>
与所有的选择。请参阅the old answer ,了解更多实现细节和代码示例。
最后,您应该修复 width: "200px"
至width: 200
。 width
的值属性应该是数字或可以转换为数字的字符串。 px
的用法or 等后缀是错误的。下一个建议修复将删除 index: 'UnitID'
和所有其他index
来自colModel
的属性,如果 index
的值属性与 name
的值相同属性。
关于jqgrid colmodel editoptions加载json结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341511/