Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I ModelBind a many-to-many relationship with MVC 3 and Entity Framework Code First?
    primarykey
    data
    text
    <p>I'm coming across the same problem in my MVC 3 applications. I've got a view to create an new product and that product can be assigned to one or more categories. Here are my EF Code First Model Classes:</p> <pre><code>public class Product { public int ProductID { get; set; } public string Name { get; set; } public virtual ICollection&lt;Category&gt; Categories { get; set; } } public class Category { public int CategoryID { get; set; } public string Name { get; set; } public virtual ICollection&lt;Product&gt; Products { get; set; } } </code></pre> <p>So, I create a view model for the create product view and include the product and a list of the categories:</p> <pre><code>public class ProductEditViewModel { public Product Product { get; set; } public List&lt;SelectListItem&gt; CategorySelections { get; set; } public ProductEditViewModel(Product product, List&lt;Category&gt; categories) { this.Product = product; CategorySelections = categories.Select(c =&gt; new SelectListItem() { Text = c.Name, Value = c.CategoryID.ToString(), Selected = (product != null ? product.Categories.Contains(c) : false) }).ToList(); } } </code></pre> <p>So, I render a view with an input for the name and a list of checkboxes for each category (named "Product.Categories"). When my form gets posted back I want to save the product with its associated categories (or if the ModelState is invalid, to redisplay the view with the category selections the user made intact).</p> <pre><code>[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())); } </code></pre> <p>When i do that and select one or more categories, the ModelState is invalid and it returns the Edit view with the following validation error:</p> <blockquote> <p>The value '25,2' is invalid. // 25 and 2 being the CategoryIDs</p> </blockquote> <p>It makes sense to me that it can't bind 25 and 2 into actual category objects, but is there a standard way to use a custom ModelBinder that would allow me to translate IDs into Categories and attach them to the context?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload