我正在尝试为book(id为1)创建编辑表单,我希望选择列表选择从数据库中检索的现有作者。 id为1的那本书的作者身份为1,但HTML并未显示该书的ID为1的选定作者。
我觉得这个论点有问题 ViewData [“SelectedAuthors”]为IEnumerable 在MultiSelectList函数 在Book.ascx源文件
另一个问题是,如何使用MultiSelectList将“first_name”和“last_name”结合起来进行文本显示?我只能选择“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();
//
// GET: /StoreManager/Edit/5
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()
};
//I have debug and have seen that the SelectedAuthors list has one author_id as 1
return View(viewModel);
}
}
}
StoreManagerController的“edit”方法的Book.ascx(部分视图)
<%@ 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>
<% } %>
Book.ascx局部视图的HTML结果
<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>
答案 0 :(得分:0)
您正在使用需要绑定到作为集合的模型属性的多选列表。在您的情况下,您绑定到"author_id"
,它只能包含一个选定的项ID。此外,您在部分中使用ViewData["authors"]
和ViewData["SelectedAuthors"]
,但在控制器操作中,不清楚这些属性是如何填充的。
答案 1 :(得分:0)
现在已经解决了,我没有在“edit.aspx”视图中将“SelectedAuthors”提供给“Book.ascx”的局部视图
<%: Html.EditorFor(model => model.Book,
new { Authors = Model.Authors, Categories = Model.Categories, SelectedAuthors = Model.SelectedAuthors }) %>