How to get a separate value from the LINQ query for a drop-down list

advertisements

My Model is:

    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; }

   }

My Controller is like :

    [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");
        }

    }

Now in HrModel.YearList I have to pass Year column from the table 'EmployeeSalary', for the use of dropdownlist. The table contains multiple entries with the same Year, due to which dropdownlist is populated with repeating Years.

I'm using following code by selecting a.Year from the table but it's throwing another error:

    var Year = (from a in dbContext.EmployeeSalaries.Where(f => f.UserName == UserName) select a.Year).Distinct();

Error in code line:

    HrModel.YearList = Year.ToList();


You are selecting the distinct Year property(a string), but you assign the list to a property of type List<EmployeeSalary>, that doesn't work and explains the error.

You could GroupBy this property and just take the first of each group:

HrModel.YearList = dbContext.EmployeeSalaries
    .Where(f => f.UserName == UserName)
    .GroupBy(f => f.Year)
    .Select(g => g.First())
    .ToList();

If you don't want to take the first of each group you have to explain the logic.