問題: 使用 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中文網其他相關文章!