首页 > 后端开发 > C++ > 为什么我的 ASP.NET MVC $.post 调用 jqGrid 在下拉列表中返回未定义的值?

为什么我的 ASP.NET MVC $.post 调用 jqGrid 在下拉列表中返回未定义的值?

Patricia Arquette
发布: 2025-01-11 08:49:43
原创
999 人浏览过

Why is my ASP.NET MVC $.post Call to jqGrid Returning an Undefined Value in the Dropdown?

对 ASP.NET MVC 和 jqGrid 下拉列表填充问题进行故障排除

问题: 使用 ASP.NET MVC 2 $.ajax() 调用动态填充时,jqGrid 下拉列表中出现意外的“未定义”值。这是由于返回到网格的数据格式不正确造成的。 jqGrid 需要下拉值的特定格式,例如:"FE:FedEx; IN:InTime; TN:TNT"。 使用 StringBuilder 进行数据格式化会产生额外的引号和尾随分号。

分析:最初的方法使用ContentResult(sb.ToString())返回数据。虽然功能齐全,但效率较低并且容易出现格式错误。

解决方案: 利用 dataUrlbuildSelect 中 jqGrid 的 editoptionssearchoptions 属性提供了更干净、更强大的解决方案。 这消除了手动字符串格式化。 dataUrl 指定数据源,buildSelect 处理格式。

使用 dataUrlbuildSelect 的示例:

<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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板