The biggest problem with sending values ββfor the many-to-many relationship is the lack of a direct field to bind to your model. Here, viewing models become very convenient that you are already using, but not quite right for this.
First you need a SelectList , which may just be IEnumerable<SelectListItem> . It will contain all available options, which is quite simple. So, in your view model:
public IEnumerable<SelectListItem> CategoryChoices { get; set; }
And in your action:
carEditViewModel.CategoryChoices = approvalList.Select(m => new SelectListItem { Text = c.Name, Value = c.Id.ToString() });
Please note that I do not install Selected : we will allow HtmlHelper to handle this. I also do not deal with MultiSelectList .
Now you will also need something to send messages back, since your values ββwill be identifiers, we will use List<int> , so in your view model:
private List<int> selectedCategories; public List<int> SelectedCategories { get { if (selectCategories == null) { selectedCategories = Categories.Select(m => m.Id).ToList(); } return selectedCategories; } set { selectedCategories = value; } }
Here is a bit. The set method of the property is simple: when we return the post value, just set selectedCategories for it. get little more complicated: here we need to condense the list of category objects (called Categories here because I donβt know where it comes from) into a simple list of identifiers for these categories.
Now, in your opinion:
@Html.ListBoxFor(m => m.SelectedCategories, Model.CategoryChoices)
That is all you need. You are using the ListBox control so that it is already a list with multiple selections. And, tying it to the list of all currently selected identifiers, he knows which elements to automatically select in the SelectListItem list, he gets from Model.CategoryChoices .
In your post, after that you need to translate these identifiers into related objects:
var newCategories = repository.Categories.Where(m => carEditViewModel.SelectedCategories.Contains(m.Id));
Then you can manually set your model categories to this new list:
car.Categories = newCategories;