我正在尝试为书籍(id 为 1)创建编辑表单,我希望选择列表选择从数据库中检索到的现有作者。 id 为 1 的那本书有一个 id 为 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 的“编辑”方法的 Book.ascx(部分 View )
<%@ 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 部分 View 的 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>
最佳答案
您正在使用需要绑定(bind)到作为集合的模型属性的多选列表。在您的情况下,您绑定(bind)到 "author_id"
,它只能包含一个选定的项目 ID。此外,您还在局部使用 ViewData["authors"]
和 ViewData["SelectedAuthors"]
但在 Controller 操作中不清楚这些属性是如何填充的。
关于c# - 在 ASP.NET MVC 中使用 MultiSelectList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3264586/