排序下拉列表

本文关键字:下拉列表 排序 | 更新日期: 2023-09-27 17:56:48

我有下拉列表,我需要排序。我试过了,但我对此表示怀疑。

我的代码看起来像,

    public ActionResult GetAgencyState(string statecode)
    {
        _logger.Info("GetAgencyState: " + statecode);
        AuthUserProfile profile = _sessionHelper.Get<AuthUserProfile>(SessionConstant.LightAUP);
        List<Light_AgenciesState> getAgenciesState = _mcpServiceHelper.GetAgenciesState(
            profile.au_key.ToString(), profile.officernode.ToString(), profile.role, statecode);
        Dictionary<string, string> agenciesState = new Dictionary<string, string>();
        agenciesState = getAgenciesState.ToDictionary(x => x.AgencyKey.ToString(), x => x.AgencyName);
        agenciesState = agenciesState.Count() == 0 ? null : agenciesState;
        agenciesState.OrderBy(agenciesState => agenciesState.Value);
        return Json(agenciesState, JsonRequestBehavior.AllowGet);
    }

我在这一行中收到错误:

     agenciesState.OrderBy(agenciesState => agenciesState.Value);

我的JavaScript代码调用此方法:

var GetAgencyStateUrl = "/Import/GetAgencyState";
 function OwnerStateFunction() {
var selectedVal = $("option:selected", $("#Ownerstate")).attr("Value");
if (selectedVal != "- select -" && selectedVal != "") {
    $.get(GetAgencyStateUrl, { 'statecode': selectedVal }, function (data) {
  $('#AgentPhone').val("");
        $.map(data, function (value, key) {
            var opt = "<option value='"" + key + "'">" + value + "</option>";
            $("#OwnerAgency").append(opt);
        });
    }   

如何实现排序?

排序下拉列表

这个替换你的错误行

 agenciesState.OrderBy(a => a.Value);
首先,

您不返回排序的集合。使用 agenciesState.OrderBy(agenciesState => agenciesState.Value); 不会将排序的集合分配给变量。它必须是

var sorted = agenciesState.OrderBy(agenciesState => agenciesState.Value);
return Json(sorted, JsonRequestBehavior.AllowGet);

但是,您的代码还有其他问题,包括前一行

agenciesState = agenciesState.Count() == 0 ? null : agenciesState;

这意味着agenciesState可能会null在这种情况下,以下行将引发异常。

在任何情况下,您都不应该返回字典。控制器代码可以只是

public ActionResult GetAgencyState(string statecode)
{
    ....
    List<Light_AgenciesState> getAgenciesState = _mcpServiceHelper.GetAgenciesState(....);
    var agenciesState = getAgenciesState.Select(a => new { Value = a.AgencyKey, Name = a.AgencyName });
}

然后在 Ajax 函数中

var url = '@Url.Action("GetAgencyState", "Import")'; // dont hardcode!
var ownerAgency = $("#OwnerAgency"); // cache it
$("#Ownerstate").change(function() {
  var statecode = $(this).val();
  if (!statecode) {
    return;
  }
  $.get(url, { statecode: statecode }, function (data) {
    ownerAgency.empty(); // remove existing options
    $.each(data, function(index, item) {
      ownerAgency.append($('</option>').val(item.Value).text(item.Name));
    });
  });
});

并从 HTML 标记中删除onchange="OwnerStateFunction()"