问题: 使用 ASP.NET MVC 2 $.ajax() 调用动态填充时,jqGrid 下拉列表中出现意外的“未定义”值。这是由于返回到网格的数据格式不正确造成的。 jqGrid 需要下拉值的特定格式,例如:"FE:FedEx; IN:InTime; TN:TNT"
。 使用 StringBuilder 进行数据格式化会产生额外的引号和尾随分号。
分析:最初的方法使用ContentResult(sb.ToString())
返回数据。虽然功能齐全,但效率较低并且容易出现格式错误。
解决方案: 利用 dataUrl
或 buildSelect
中 jqGrid 的 editoptions
和 searchoptions
属性提供了更干净、更强大的解决方案。 这消除了手动字符串格式化。 dataUrl
指定数据源,buildSelect
处理格式。
使用 dataUrl
和 buildSelect
的示例:
<code class="language-javascript">{ name: 'destinations', editable: true, edittype: 'select', editoptions: { dataUrl: '<%= Url.Action("GetDestinationList", "Home") %>', buildSelect: function(response) { var s = ''; if (response && response.length) { for (var i = 0; i < response.length; i++) { s += response[i] + ';'; //Note the semicolon placement } } return s; // Removed trailing "" } } }</code>
HTTP 方法注意事项:
如果 dataUrl
优先使用 POST 请求而不是 GET,请在服务器端将 Json(allDestinations, JsonRequestBehavior.AllowGet)
替换为 Json(allDestinations)
并将 ajaxSelectOptions: { type: "POST" }
添加到 jqGrid 选项。
优化buildSelect
功能:
提供的 buildSelect
函数可以稍微优化以提高清晰度和效率(尽管功能与原始函数类似):
<code class="language-javascript">buildSelect: function(response) { return (response && response.length) ? response.join(';') : ''; }</code>
这种修改后的方法提供了一种更易于维护且不易出错的方法来填充 jqGrid 下拉列表。
以上是为什么我的 ASP.NET MVC $.post 调用 jqGrid 在下拉列表中返回未定义的值?的详细内容。更多信息请关注PHP中文网其他相关文章!