如何根据javascript jquery中的另一个下拉列表项选择生成下拉列表项?

时间:2014-09-02 06:01:13

标签: javascript jquery asp.net-mvc-3 razor

我在这里发现了类似的问题,但那些是服务器端代码,而我想用javascript& jQuery的。以下是代码..

用于以JSON格式返回数据的C#代码

public JsonResult GetEmployeesByDepartment(int departmentId)
{
  var employees = new EmployeeInfoRepository().GetEmployeesByDepartmentId(departmentId);
  var employeeDictionary = new Dictionary<int, string>();

  foreach (var emp in employees)
  {
    if(!employeeDictionary.ContainsKey(emp.EmployeeID))
    {
      employeeDictionary.Add(emp.EmployeeID, emp.FullName);
    }
  }

  return Json(employeeDictionary, JsonRequestBehavior.AllowGet); 
}

将数据绑定到DropDownList的Javascript代码

$("#ddlDepartment").change(function () {
  var id = $("#ddlDepartment option:selected").val();
  GetEmployeeByDepartmentId(id);
});

function GetEmployeeByDepartmentId(id) {
  var postData = {
    departmentId: id
  };

  $.ajax('/Leave/GetEmployeesByDepartment', {
    method: 'GET',
    dataType: 'JSON',
    data: postData,
    async: false,

    success: function (response) {

      $.each(response, function() {
        $("#ddlEmployee").append(
          $('<option/>', {
            value: this,
            html: this
          })
        );
      });
    }
  });
} 

我也在下面尝试了成功&#34;功能,但这也不起作用。

if (response == false) {
  alert("No Employee found for this department");
} else {
  $("#ddlEmployee").html = "";
  response.each(function(index, item) {
    $("#ddlEmployee").append("<option value='item.Key'>item.Value </option>");
  });
}

按建议编辑的代码

用于以JSON格式返回数据的C#代码

public JsonResult GetEmployeesByDepartment(int departmentId)
{
  var employees = new EmployeeInfoRepository().GetEmployeesByDepartmentId(departmentId);
  return Json(employees, JsonRequestBehavior.AllowGet); 
}  

Javascript代码(仅限成功功能)

if (response == null) {
  alert("No Employee found for this department");
} else {
    $.each(response, function () {
       var option = $('<option></option>');
         option.val(response.EmployeeID);
         option.text(response.FullName);
         $("#ddlEmployee").append(option);
    });
}  

&#34;成功&#34;调用函数并返回一个对象数组。但是,数据仍未绑定到&#34; ddlEmployee&#34;。

最终解决方案
目前使用以下代码 -

执行此操作
$("#ddlEmployee").empty();
$.each(response, function (key, value) {
  $("#ddlEmployee").append('<option value=' + value.EmployeeID + '>' + value.FullName + '</option>');
});

1 个答案:

答案 0 :(得分:0)

不确定为什么要归还字典。我假设EmployeeID是唯一的,因此可以简化为:

var employees = new EmployeeInfoRepository()
  .GetEmployeesByDepartmentId(departmentId)
  .Select(e => new
  {
    ID = e.EmployeeID,
    Name = e.FullName
  }
return Json(employees, JsonRequestBehavior.AllowGet); 

并在脚本中(成功函数)

$.each(response, function() {
  var option = $('<option></option>');
  option.val(response.ID);
  option.text(response.Name);
  $("#ddlEmployee").append(option);
});