我的模特是:
public class HRModel
{
[Required(ErrorMessage = "Please select Year")]
public string SelectedYear { get; set; }
public List<EmployeeSalary> YearList { get; set; }
[Required(ErrorMessage = "Please select Month")]
public int SelectedMonthId { get; set; }
public List<EmployeeSalary> MonthList { get; set; }
public int UserId { get; set; }
public string Username { get; set; }
public string URL { get; set; }
public string Year { get; set; }
public int MonthId { get; set; }
public int Month { get; set; }
}
我的控制器就像:
[HttpGet]
public ActionResult Salary()
{
try
{
string UserName = User.Identity.Name.ToString();
ViewBag.UserId = UserName;
HRModel HrModel = new HRModel();
var Year = (from a in dbContext.EmployeeSalaries.Where(f => f.UserName == UserName) select a);
HrModel.YearList = Year.ToList();
return View(HrModel);
}
catch (Exception ex)
{
return RedirectToAction("Index");
}
}
现在在 HrModel.YearList 中,我必须从表'EmployeeSalary'中传递Year列,以便使用dropdownlist。该表包含多个具有相同年份的条目,因为下拉列表中填充了重复的年份。
我通过从表中选择 a.Year 来使用以下代码,但它又引发了另一个错误:
var Year = (from a in dbContext.EmployeeSalaries.Where(f => f.UserName == UserName) select a.Year).Distinct();
代码行出错:
HrModel.YearList = Year.ToList();
答案 0 :(得分:2)
您正在选择不同的Year
属性(字符串),但是您将列表分配给类型为List<EmployeeSalary>
的属性,该属性不起作用并解释错误。
你可以GroupBy
这个属性,然后只取每组中的第一个:
HrModel.YearList = dbContext.EmployeeSalaries
.Where(f => f.UserName == UserName)
.GroupBy(f => f.Year)
.Select(g => g.First())
.ToList();
如果你不想参加每组的第一组,你必须解释逻辑。
答案 1 :(得分:0)
你必须将年份转换为列表。例如:
var lstYear = Year.Select(new EmployeeSalary{}).ToList();