这是我的型号
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" })
请参阅此问题;不能将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);
}
我们可以检查model.Categories
中是否存在Exists()
,而不是从model.Categories
中选择CategoryId
,然后检查s.CategoryId
是否在该列表中,CategoryId
与s.CategoryId
相同。
在"选择";作为问号条件。
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;