如何使SelectListItem根据条件选择true或false [英] How to make SelectListItem Selected true or false on based on condition

查看:278
本文介绍了如何使SelectListItem根据条件选择true或false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模型

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


    }

我需要将Selected设置为如果ID存在于NewsViewModel.Categories集合中,则为True

I need to set Selected to be True if id exists in NewsViewModel.Categories collection

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

}

而在View中:

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


推荐答案

请参阅这个问题;你不能使用包含与非原始类型(例如类别在这种情况下)。用于编写您的查询的另一种方法可以解决这个限制:

See this question; you cannot use Contains with non-primitive types (like Category in this case). A different way to write your query that works around this limitation would be:

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

而不是选择 CategoryId s从 model.Categories 然后检查如果 s.CategoryId 在该列表中,我们可以查看如果 Exists() model.Categories 中的 CategoryId s.CategoryId 相同。

Instead of selecting the CategoryIds from model.Categories and then checking if s.CategoryId is in that list, we can check to see if there Exists() an item in model.Categories for which the CategoryId is the same as s.CategoryId.

这篇关于如何使SelectListItem根据条件选择true或false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆