MVC (Razor) 中单个 table 的级联下拉列表

Cascading dropdown lists from single table in MVC (Razor)

我的查询是制作两个级联下拉列表,从单个 table 中获取数据。 我的 table 就像:

我的控制器:

    public JsonResult GetYear()
    {
        string UserName = User.Identity.Name.ToString();

        return Json(dbContext.EmployeeSalaries.Where(f => f.UserName == UserName).GroupBy(f => f.Year).Select(g => g.FirstOrDefault()).ToList(), JsonRequestBehavior.AllowGet);
    }

    public JsonResult GetMonth(string year)
    {
        string UserName = User.Identity.Name.ToString();

        IEnumerable<string> monthList = dbContext.EmployeeSalaries.Where(a => a.Year == year && a.UserName == UserName).Select(u => u.Month).ToList();

        return Json(monthList);
    }

这里我先填充年下拉列表,根据选择填充月下拉列表。例如这里对于UserName = 1832,有一年即2017年,三个月(5月、6月、7月)的数据。因此,当用户选择 2017 年时,月份下拉列表应填充 May、June、July。

问题:月份下拉列表在列表中显示'undefined'。

查看和jQuery使用:

      @Html.DropDownList("ddlYear", new SelectList(string.Empty, "Value", "Text"), "Please select year", new { @style = "width:250px;" })

      @Html.DropDownList("ddlMonth", new SelectList(string.Empty, "Value", "Text"), "Please select month", new { @style = "width:250px;" })

      <script type="text/javascript">
      $.ajax({
        type: "GET",
        url: "/SalaryProcess/GetYear",
        datatype: "Json",
        success: function (data) {
            $.each(data, function (index, value) {
                $('#ddlYear').append('<option value="' + value.Year + '">' + value.Year + '</option>');
            });
        }
    });

    $('#ddlYear').change(function () {
       // $('#ddlMonth').empty();
        $.ajax({
            type: "POST",
            url: "/SalaryProcess/GetMonth",
            data: { year: $('#ddlYear').val() },
            datatype: "Json",
            success: function (data) {
                $.each(data, function (index, value) {
                    $('#ddlMonth').append('<option value="' + value.MonthId + '">' + value.Month + '</option>');
                });
            }
        });
    });
});
</script>

请提出解决此问题的建议。

您的 GetMonth 方法有问题。您仅从 EmployeeSalaries table 中选择 month 列,但在视图中您将它们用作模型属性(value.monthIdvalue.month)。请使用以下代码,它应该可以工作:

public JsonResult GetMonth(string year)
{
    string UserName = User.Identity.Name.ToString();

    var monthList = dbContext.EmployeeSalaries
        .Where(a => a.Year == year && a.UserName == UserName)
        .Select(x => new { MonthId = x.MonthId, Month = x.Month });
    return Json(monthList);
}