这是我的模特
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设置为Trueprivate 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" })
答案 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;