I am trying to create an editing form for a book (with identifier 1), I want the selection list to select an existing author who was retrieved from the database. In this book with id 1, there is an author with identifier 1, but HTML does not display the selected author with identifier 1 for this book.
I feel that something is wrong with the ViewData ["SelectedAuthors"] argument as IEnumerable in the MultiSelectList function in the original Book.ascx file
Another problem is how to use MultiSelectList to combine "first_name" and "last_name" to display text? I can only select "first_name"
StoreManagerViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BookStore.Models;
namespace BookStore.ViewModels
{
public class StoreManagerViewModel
{
public book Book { get; set; }
public List<author> Authors { get; set; }
public List<category> Categories { get; set; }
public List<int> SelectedAuthors { get; set; }
}
}
StoreManagerController.cs
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookStore.Models;
using BookStore.ViewModels;
namespace BookStore.Controllers
{
public class StoreManagerController : Controller
{
BookStoreEntities storeDB = new BookStoreEntities();
public ActionResult Edit(int id)
{
var viewModel = new StoreManagerViewModel
{
Book = storeDB.books.Single(a => a.book_id == id),
Categories = storeDB.categories.ToList(),
Authors = storeDB.authors.ToList(),
SelectedAuthors = (from a in storeDB.books.Single(b => b.book_id == id).authors
select a.author_id
).ToList()
};
return View(viewModel);
}
}
}
Book.ascx( ) "edit" StoreManagerController
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BookStore.Models.book>" %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.authors) %>
</div>
<div class="editor-field">
<%: Html.ListBox("author_id", new MultiSelectList(ViewData["authors"] as IEnumerable, "author_id", "first_name", ViewData["SelectedAuthors"] as IEnumerable))%>
</div>
<% } %>
HTML Book.ascx
<select id="Book_author_id" multiple="multiple" name="Book.author_id">
<option value="1">Bikkhu</option>
<option value="2">Buddha</option>
<option value="3">William</option>
<option value="4">Anthony</option>
</select>