Resolving the "undefined" Value in ASP.NET MVC jqGrid Dropdowns
When dynamically populating jqGrid dropdowns during data editing, an unwanted "undefined" value frequently appears. This stems from inconsistencies between the data structure jqGrid expects and the data delivery method.
Correct jqGrid Data Format:
The ideal format for the dropdown's value is: value: "FE:FedEx; IN:InTime; TN:TNT"
Problem with Current Method:
The current approach uses ASP.NET MVC with jQuery's $.ajax()
to fetch dropdown data. A StringBuilder
manipulates the retrieved data to match jqGrid's format, but an extra "undefined" entry persists.
Debugging Findings:
FireBug debugging indicates that extra quotes introduced by sb.ToString()
are the culprit. jqGrid adds its own quotes, leading to doubled-up quotes and the "undefined" issue.
A Superior Solution: Using dataUrl
and buildSelect
Instead of directly manipulating the value
property, a more robust solution involves using jqGrid's dataUrl
and buildSelect
properties within editoptions
or searchoptions
. These allow for customized data fetching and formatting.
Example dataUrl
Action:
public JsonResult GetDestinationList() {
List allDestinations = GetAllDestinations();
return Json(allDestinations, JsonRequestBehavior.AllowGet);
}
Example buildSelect
Function:
buildSelect: function(data) {
var s = '';
if (data && data.length) {
for (var i = 0, l = data.length; i
Updated editoptions
:
{
name: 'destinations',
editable: true,
edittype: 'select',
editoptions: {
dataUrl: '/YourController/GetDestinationList', // Replace with your controller action path
buildSelect: function(data) {
// ... (buildSelect function from above) ...
}
}
}
Important Notes:
Json(allDestinations);
without JsonRequestBehavior.AllowGet
, but you'll need to add ajaxSelectOptions: { type: "POST" }
to your jqGrid options.buildSelect
is called within the $.ajax()
success handler, making jQuery.parseJSON(data.responseText)
unnecessary.This revised approach provides a cleaner, more efficient, and less error-prone method for managing jqGrid dropdowns, eliminating the "undefined" value issue. Remember to replace /YourController/GetDestinationList
with the actual path to your controller action.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3