Linq MVC(Razor)中单个表的级联下拉列表
我的查询是创建两个级联下拉列表,从单个表中获取数据。 我的桌子是这样的: 我的控制器: 这里我首先填写年份下拉列表,根据选择填写月份下拉列表。例如,此处用户名=1832,有一年(即2017年)和三个月(5月、6月、7月)的数据。因此,当用户选择2017年时,月份下拉列表应填充五月、六月、七月 问题:月份下拉列表在列表中显示“未定义” 使用的视图和jQuery:Linq MVC(Razor)中单个表的级联下拉列表,linq,asp.net-mvc-4,Linq,Asp.net Mvc 4,我的查询是创建两个级联下拉列表,从单个表中获取数据。 我的桌子是这样的: 我的控制器: 这里我首先填写年份下拉列表,根据选择填写月份下拉列表。例如,此处用户名=1832,有一年(即2017年)和三个月(5月、6月、7月)的数据。因此,当用户选择2017年时,月份下拉列表应填充五月、六月、七月 问题:月份下拉列表在列表中显示“未定义” 使用的视图和jQuery: 请建议此问题的解决方案。GetMonth方法出现问题。您正在从EmployeePalaries表中仅选择month列,但在视图中,您将
请建议此问题的解决方案。GetMonth方法出现问题。您正在从EmployeePalaries表中仅选择month列,但在视图中,您将它们用作模型属性value.monthId和value.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);
}
因为返回的IEnumerable和字符串不包含属性MonthId和Month。作为旁注,您的代码还存在其他问题,建议您在发送对象的所有属性时研究代码只会降低性能创建一个只包含两个属性的匿名对象needed@Sameep巴西,请试试这个代码,如果你仍然面临这个问题,请告诉我。如果它对其他人有帮助,请投你的赞成票。谢谢,它工作得很好!谢谢你的解释。答案也被否决了!
@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>
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);
}