2017-09-06 145 views
-1

我的查詢是使兩個級聯下拉列表從單個表中獲取數據。 我的表像:從MVC中的單個表(Razor)級聯下拉列表

enter image description here

我的控制器:

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> 

請建議解決這個問題。

+0

因爲你回來'IEnumerable的'和'string'不包含屬性'MonthId'和'Month'。作爲一個方面說明,您的代碼還存在其他問題,並建議您在[DotNetFiddle](https://dotnetfiddle.net/1bPZym) –

回答

2

您的GetMonth方法出現問題。您只從EmployeeSalaries表中選擇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); 
} 
+0

中研究代碼。發送對象的所有屬性只會降低性能(創建一個匿名對象,其中包含只有2個屬性需要) –

+0

謝謝。你是對的 – Rakib

+0

@Sameep巴西,請試試這個代碼,讓我知道你是否仍然面臨這個問題。如果它投入使用,請投票支持(對其他人有幫助)。 – Rakib