SelectListItem复选框并使用Contains()自动填充

时间:2015-04-01 21:21:20

标签: c# list checkboxlist selectlistitem

我有一份课程清单。如果用户被分配到课程,那么我希望选中该复选框。为什么不接受Contains()?

视图模型:

public class ViewUserViewModel
{        
    public List<Cours> Courses { get; set; }
    public List<UserCours> UserCoursesList { get; set; }        
    public AspNetUser user { get; set; }
    public IEnumerable<SelectListItem> CourseList { get; set; }
}

控制器:

[HttpGet]
public ActionResult ViewUser(string id)
{
    ViewUserViewModel model = new ViewUserViewModel();

    model.user = db.AspNetUsers.FirstOrDefault(U => U.Id == id);

    //List all courses
    List<Cours> allCourses = db.Courses.OrderBy(c => c.CourseName).ToList();
    model.Courses = allCourses;

    //List of courses the user is assigned to
    //var selectedCourse1 = db.UserCourses.Where(uc => uc.UserId == id).ToList();
    model.UserCoursesList = db.UserCourses.Where(uc => uc.UserId == id).ToList();

    //checkbox list
    model.CourseList = allCourses.ToList().Select(x => new SelectListItem()
    {
          //Selected = selectedCourse1.Contains(x.CourseID),
          Selected = model.UserCoursesList.Contains(x.CourseID),
          Text = x.CourseName,
          Value = x.CourseID.ToString()
     });

  }

我认为Selected属性将测试List是否已分配值,然后它将返回true。相反,它是语法错误并且具有无效参数。如何将CourseList与UserCoursesList进行比较?

2 个答案:

答案 0 :(得分:1)

我认为你应该使用LINQ Any方法。您没有发布UserCours类定义,但我猜它应该有一个ID,可能看起来像这样:

public class Cours
{
    public int Id { get; set; }
    // Other properties
}

在这种情况下,您对Selected财产的检查将是:

Selected = model.UserCoursesList.Any(uc => uc.CourseID == x.CourseID) 

一些提示:

  • 在这种情况下,最好使用一些有意义的名称而不是 x,例如course。它将提高代码的可读性。
  • allCourses已经是一个列表,您无需致电ToList() 方法再次。

答案 1 :(得分:0)

更新代码:感谢Aleksandr

[HttpGet]
public ActionResult ViewUser(string id)
{
    ViewUserViewModel model = new ViewUserViewModel();

    //Which user
    model.user = db.AspNetUsers.FirstOrDefault(User => User.Id == id);

    //List all courses
    model.Courses = db.Courses.OrderBy(Courses => Courses.CourseName).ToList();

    //List of courses the user is assigned to
    model.UserCoursesList = db.UserCourses.Where(UserCourses => UserCourses.UserId == id).ToList();

    //checkbox list
    model.CourseList = model.Courses.Select(Course => new SelectListItem()
    {
           Selected = model.UserCoursesList.Any(UserCourse => UserCourse.CourseId == Course.CourseID),
           Text = Course.CourseName,
           Value = Course.CourseID.ToString()
    });
    return View(model);
}