如何使SelectListItem根据条件选择true或false

时间:2016-07-21 22:08:21

标签: c# entity-framework linq

这是我的模特

  public class NewsViewModel
    {
        public NewsViewModel()
        {

            this.Categories = new List<Category>();

        }
        public int NewsId { get; set; }
        [Required(ErrorMessage = "Please enter News Title")]
        public string NewsTitle { get; set; }
        public IEnumerable<Category> Categories { get; set; }


    }

如果在NewsViewModel.Categories集合中存在id

,我需要将Selected设置为True
private IEnumerable<SelectListItem> GetCategories()
{

    return db.Categories .Select(s=>new SelectListItem {
        Value=s.Id.ToString(),
        Text=s.Name,
        Selected = model.Categories.Select(x => x.CategoryId).Contains(s.CategoryId);

}

在视图中:

@Html.ListBoxFor(s => s.SelectedCategoriesIds, @Model.AllCategories, new { id = "DropDownList2", multiple = "multiple", @class = "form-control" })

2 个答案:

答案 0 :(得分:3)

this question;您不能将Contains与非基本类型一起使用(在本例中为Category)。编写解决此限制的查询的另一种方法是:

return db.Categories.Select(s=>new SelectListItem {
    Value=s.Id.ToString(),
    Text=s.Name,
    Selected = model.Categories.Exists(z => z.CategoryId == s.CategoryId);
}

我们可以检查CategoryId model.Categories项中是否有s.CategoryId,而不是从Exists()中选择model.Categories,然后检查CategoryId是否在该列表中1}} s.CategoryId<ActionController::Parameters {"given_name"=>"Mark", "subdomain"=>"development", "controller"=>"user", "action"=>"create", "user"=>{"given_name"=>"Mark"}} permitted: false> 相同。

答案 1 :(得分:0)

在“选定”项上添加条件作为问号条件。

    var listSiteId = (from site in db.GetSiteId().ToList()
                                      select new SelectListItem
                                      {
                                          Value = site.SITEID,
                                          Text = site.NAME,
                                          Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
                                      }).ToList();
                    ViewBag.SiteId = listSiteId;