I am facing the same problem in my MVC 3 applications. I have an idea about creating a new product, and this product can be assigned to one or more categories. Here are my first EF Code classes:
public class Product { public int ProductID { get; set; } public string Name { get; set; } public virtual ICollection<Category> Categories { get; set; } } public class Category { public int CategoryID { get; set; } public string Name { get; set; } public virtual ICollection<Product> Products { get; set; } }
So, I create a presentation model to represent the product of the product and include the product and the list of categories:
public class ProductEditViewModel { public Product Product { get; set; } public List<SelectListItem> CategorySelections { get; set; } public ProductEditViewModel(Product product, List<Category> categories) { this.Product = product; CategorySelections = categories.Select(c => new SelectListItem() { Text = c.Name, Value = c.CategoryID.ToString(), Selected = (product != null ? product.Categories.Contains(c) : false) }).ToList(); } }
So, I am visualizing a view with an input for the name and a list of flags for each category (called "Product.Categories"). When my form is submitted back, I want to save the product with the categories associated with it (or if the ModelState is invalid to re-display the view with the selected categories that the user made intact).
[HttpPost] public ActionResult Create(Product product) { if (ModelState.IsValid) { db.Products.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } return View(new ProductEditViewModel(product, db.Categories.ToList())); }
When I do this and select one or more categories, ModelState is invalid and returns an edit view with the following validation error:
The value '25, 2 'is invalid. // 25 and 2 are category identifiers
It seems to me that it cannot associate 25 and 2 with objects of the real category, but is there a standard way to use a custom ModelBinder that will allow me to translate identifiers into categories and attach them to the context?
asp.net-mvc-3 entity-framework viewmodel model-binding
Austin Aug 31 '11 at 15:54 2011-08-31 15:54
source share