【发布时间】:2014-01-17 18:01:15
【问题描述】:
我有一个 CategoryViewModel 如下:
public class CategoryViewModel
{
public string Id {get; set;}
public string Name { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
public List<string> SelectedProductIds { get; set; }
}
CategoryController 的 GET 方法使用此 CategoryViewModel 实例化一个对象并将所有产品添加到此 CategoryViewModel 对象。然后它遍历所有产品并将产品的 Selected 属性设置为 True ,这些属性包含在类别对象中:
public ActionResult CategoryController(string categoryId)
{
CategoryDbContext db = new CategoryDbContext();
CategoryRepository CategoryRepo = new CategoryRepository(db);
ProductRepository ProductRepo = new ProductRepository(db);
Category category = CategoryRepo.GetCategory(categoryId);
CategoryViewModel categoryView = new CategoryViewModel()
{
Id = category.Id,
Name = category.Name,
Products = from product in ProductRepo.GetAllProducts()
select new SelectListItem { Text = product.Name, Value = product.Id, Selected = false}
};
foreach (var product in category.Products)
{
categoryView.Products.Where(x => x.Value == product.Id).FirstOrDefault().Selected = true;
}
return View(categoryView);
}
使用调试器,我观察到 foreach 执行,但 categoryView 的所有具有 Selected 属性的产品仍设置为 False。
但是,这个工作正常:
public ActionResult CategoryController(string categoryId)
{
CategoryDbContext db = new CategoryDbContext();
CategoryRepository CategoryRepo = new CategoryRepository(db);
ProductRepository ProductRepo = new ProductRepository(db);
Category category = CategoryRepo.GetCategory(categoryId);
CategoryViewModel categoryView = new CategoryViewModel()
{
Id = category.Id,
Name = category.Name,
Products = from product in ProductRepo.GetAllProducts()
select new SelectListItem { Text = product.Name, Value = product.Id, Selected = category.Products.Contains(product)}
};
return View(categoryView);
}
谁能解释一下区别以及为什么第一个不起作用?
编辑: 我使用的是 EF 6,产品和类别以多对多关系存储在数据库中。
【问题讨论】:
-
可能在您的 foreach 循环中,该行会引发异常。因为引用类型默认值为 null,并且 null 没有 Selected 属性。您确定它不会引发异常吗?
-
@Selman22 是的,它处于调试模式,如果尝试设置空引用的属性,则会引发错误。但会再次测试以确保。
-
那么我的假设是正确的 =) 检查我的答案,然后再试一次
-
@Selman22 抱歉我的回答含糊。我想说的是“是的,它在空引用的情况下抛出异常,但在这种情况下我没有收到异常。”。
标签: c# asp.net-mvc selected selectlistitem