If you try to solve the problem for jqGrid only you can choose another way.
You can use dataUrl and buildSelect properties of editoptions or searchoptions instead of value
property. This features are introduced specially for the usage in AJAX. The dataUrl defines url provided results in the form like
<select><option value="1">One</option> <option value="2">Two</option></select>
If for you is easer to return JSON results from the server your custom function buildSelect will help. As the parameter it receive the data send from the server and it should return the string <select><option>...</option></select>
. In the way you will achieve better results.
If you do decide to stay at your old way you should at least fix your code to following
foreach (var q in query)
{
if (sb.Length != 0)
sb.Append(';');
sb.Append(q.Destination); // instead of sb.Append("ID");
sb.Append(':');
sb.Append(q.Destination);
}
to has "FedEx:FedEx;InTime:InTime;TNT:TNT"
instead of "ID:FedEx; ID:InTime; ID:TNT; "
.
UPDATED: You asked for a small example. Let us you can for example get all different values of the destinations strings as a List<string>
and the name of this Method is GetAllDestinations
. Then your action used by dataUrl can look like
public JsonResult GetDestinationList() {
List<string> allDestinations = GetAllDestinations();
Json(allDestinations, JsonRequestBehavior.AllowGet);
}
To use this action inside of editoptions or searchoptions of jqGrid you can define about following
{ name: 'destinations', ditable: true, edittype:'select',
editoptions: { dataUrl:'<%= Url.Action("GetDestinationList","Home") %>',
buildSelect: function(data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l=response.length; i<l ; i++) {
var ri = response[i];
s += '<option value="'+ri+'">'+ri+'</option>';
}
}
return s + "</select>";
}
}
}
If you don't want have actions which be used per HTTP GET you can use Json(allDestinations);
instead of Json(allDestinations, JsonRequestBehavior.AllowGet);
in the GetDestinationList
action, but add to the list of jqGrid options an additional option
ajaxSelectOptions: { type: "POST" }
UPDATED 2: The answer is already old. In the interim the code of jqGrid where buildSelect
will be called was changed. Now the buildSelect
will be used inside of success
handler of jQuery.ajax
(see here) instead of the complete
handler before (see the post and the post for example). So in the current version of jqGrid the line
var response = jQuery.parseJSON(data.responseText);
is not needed. The data
is typically the parsed JSON data and so the lines
buildSelect: function(data) {
var response = jQuery.parseJSON(data.responseText);
in the code above can be replaced to
buildSelect: function(response) {