Ho una categoria ViewModel come segue:
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; }
}
Il metodo GET di CategoryController utilizza questa categoria ViewModel per istanziare un oggetto e aggiunge tutti i prodotti a questo oggetto CategoryViewModel. Quindi itera attraverso tutti i prodotti e imposta la proprietà selezionata dei prodotti su true che sono inclusi nell'oggetto della categoria:
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);
}
Usando il debugger, osservo che Forech esegue, ma CategoryView ha tutti i prodotti con proprietà selezionate ancora impostate su False.
Tuttavia, questo funziona bene:
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);
}
Qualcuno può spiegare la differenza e perché il primo non funziona?
MODIFICARE:Sto usando EF 6 e i prodotti e le categorie sono archiviati nel database con una relazione molti-a-molti.