I am trying to have a ListBox where one can select multiple Tags for a Quote that is beeing created in the Form. Everything is rendered fine, all options that should be shown are shown in the ListBox, but even though I selected some, the corresponding Collection in the returned ViewModel is empty or null.
I simplified the model for the sake of my question and it basically only has Quotes with a many-to-many relationship to Tags. So, when I want to create a new Quote I have to give it Content and a Collection of Tags.
So I have a model like this:
public class Quote
{
public int Id { get; private set; }
[Required]
public string Content { get; set; }
public ICollection Tags { get; private set; }
}
and
public class Tag
{
public int Id { get; set; }
[Required]
public string Designation { get; set; }
public ICollection Quotes { get; private set; }
}
ViewModel:
public class QuoteCreateViewModel
{
public IEnumerable Tags { get; set; }
public Quote Quote { get; set; }
public QuoteCreateViewModel(Quote quote, IList tags)
{
Quote = quote;
Tags = tags;
}
}
QuotesController:
public ActionResult Create()
{
QuoteCreateViewModel viewModel =
new QuoteCreateViewModel(new Quote(), _context.Tags.ToList());
return View(viewModel);
}
[HttpPost]
public ActionResult Create(QuoteCreateViewModel quoteCreateViewModel)
{
Quote quote = quoteCreateViewModel.Quote;
_context.Quotes.Add(quote);
_context.SaveChanges();
return RedirectToAction("Index");
And the corresponding View:
@model CiteMe.ViewModels.QuoteCreateViewModel
@using (Html.BeginForm("Create", "Quotes"))
{
@Html.LabelFor(m => m.Quote.Content)
@Html.TextBoxFor(m => m.Quote.Content, new { @class = "form-control"})
@Html.LabelFor(m => m.Quote.Tags)
@Html.ListBoxFor(m => m.Quote.Tags, new MultiSelectList(Model.Tags, "Id", "Designation"), new { @class = "form-control", multiple = "multiple" })
Save
}
As far as I am concerned @Html.ListBoxFor(m => m.Quote.Tags, new MultiSelectList(Model.Tags, "Id", "Designation"), new { @class = "form-control", multiple = "multiple" }) should do the trick for me. I have also tried an approach I found here, but it delivers the same results. Empty Collections even though something was selected or null instead of an instance of the Collection.