0

我有一个课程清单。如果将用户分配给课程,那么我希望选中该复选框。为什么不接受 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 进行比较?

4

2 回答 2

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() 再次调用方法。
于 2015-04-01T21:35:55.153 回答
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);
}
于 2015-04-02T15:37:15.417 回答