I'm trying to populate drowdown list in jquery from my controller method which return ordered dictionary object for key value pair. but when my drop down list filled, it does not preserve the order why is is like so
Here is my controller action method code ..
public JsonResult GetRolesByGroupId(string groupCode)
{
var getRoleList = BusinessLayer.GetRoles()
.Where(x => x.GroupCode == groupCode)
.Select(i => new {i.RoleId, i.RoleDesc})
.OrderBy(i => i.RoleDesc)
.ToList();
//var groupCodeList = getRoleList.Where(x => x.GroupCode == groupCode).OrderBy(o => o.RoleDesc)
// .ToDictionary(g => g.RoleId.ToString(), g => g.RoleDesc);
Dictionary<string, string> objlist = new Dictionary<string, string>();
getRoleList.ForEach(e=>objlist.Add(e.RoleId.ToString(),e.RoleDesc));
return Json(objlist, JsonRequestBehavior.AllowGet);
}
and here is my jquery code..
$('#groupCodeList').on("change",
function () {
if ($('#groupCodeList option:selected').text() === "All") {
$('#RoleId').empty();
$('#RoleId').append('<option value=""></option>');
$('#RoleId').append('<option value="">All</option>');
} else {
if ($('#groupCodeList option:selected').text()) {
$.getJSON(getRolesUrl,
{ groupCode: $('#groupCodeList').val() },
function (data) {
$('#RoleId').empty();
$('#RoleId').append('<option value="">--Select--</option>');
$.each(data,
function (key, val) {
$('#RoleId').append('<option value="' + key + '">' + val + '</option>');
});
});
} else {
$('#RoleId').empty();
$('#RoleId').append('<option value=""></option>');
//selectedCategory = "";
}
}
What is the issue here, can someone help me, how to bind dropdown with sorted dictionary/list object with json in jquery.? help appreciated.
If you want to fill dropdown and preserve order list, there are two ways, you can refer to them, hope them can help :
One way:
you can remove Dictionary<string, string> objlist
, just return ordered getRoleList
.
like:
return Json(getRoleList, JsonRequestBehavior.AllowGet);
Then change below:
$.each(data,
function (key, val) {
$('#RoleId').append('<option value="' + key + '">' + val + '</option>');
});
with:
$.each(data, function (i, item) {
$("#RoleId").append(`<option value="${item.roleId}">${item.roleDesc}</option>`);
});
Second way:
Exchange the Dictionary<string, string> objlist
key and value like:
getRoleList.ForEach(e => objlist.Add(e.RoleDesc,e.RoleId.ToString()));
Then change the code like:
$.each(data,
function (key, val) {
$('#RoleId').append('<option value="' + val + '">' + key + '</option>');
});