我的查詢是使兩個級聯下拉列表從單個表中獲取數據。 我的表像:從MVC中的單個表(Razor)級聯下拉列表
我的控制器:
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年,和三個月(五月,六月,七月)的數據。因此,當用戶選擇2017年時,月份下拉列表應該填充5月,6月,7月。
問題:月份下拉列表在列表中顯示「未定義」。
查看和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>
請建議解決這個問題。
因爲你回來'IEnumerable的'和'string'不包含屬性'MonthId'和'Month'。作爲一個方面說明,您的代碼還存在其他問題,並建議您在[DotNetFiddle](https://dotnetfiddle.net/1bPZym) –