我想擁有一個列表框,其中可以選擇多個標籤爲beeing在窗體中創建一個報價。一切都很好,應該顯示的所有選項都顯示在列表框中,但即使我選擇了一些,返回的ViewModel中的相應Collection也是空的或空的。ASP.NET MVC5剃刀列表框與MultiSelectList形式
爲了我的問題,我簡化了模型,它基本上只包含與標籤有多對多關係的引用。所以,當我想創建一個新的報價,我必須給它內容和標籤集合。
所以我有這樣一個模型:
public class Quote
{
public int Id { get; private set; }
[Required]
public string Content { get; set; }
public ICollection<Tag> Tags { get; private set; }
}
和
public class Tag
{
public int Id { get; set; }
[Required]
public string Designation { get; set; }
public ICollection<Quote> Quotes { get; private set; }
}
視圖模型:
public class QuoteCreateViewModel
{
public IEnumerable<Tag> Tags { get; set; }
public Quote Quote { get; set; }
public QuoteCreateViewModel(Quote quote, IList<Tag> 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");
以及相應的視圖:
@model CiteMe.ViewModels.QuoteCreateViewModel
@using (Html.BeginForm("Create", "Quotes"))
{
<div class="form-group">
@Html.LabelFor(m => m.Quote.Content)
@Html.TextBoxFor(m => m.Quote.Content, new { @class = "form-control"})
</div>
<div class="form-group">
@Html.LabelFor(m => m.Quote.Tags)
@Html.ListBoxFor(m => m.Quote.Tags, new MultiSelectList(Model.Tags, "Id", "Designation"), new { @class = "form-control", multiple = "multiple" })
</div>
<button type="submit" class="btn btn-primary">Save</button>
}
至於我擔心@Html.ListBoxFor(m => m.Quote.Tags, new MultiSelectList(Model.Tags, "Id", "Designation"), new { @class = "form-control", multiple = "multiple" })
應該爲我做的伎倆。我也嘗試了一種方法,我發現here,但它提供了相同的結果。即使選擇了某些內容的空集合,也可以爲null,而不是集合的實例。