[英]using MultiSelectList in ASP.NET MVC
我正在嘗試為book創建編輯表單(ID為1),我希望選擇列表選擇從數據庫中檢索的現有作者。 id為1的書具有id為1的作者,但HTML不顯示該書的id為1的選定作者。
我覺得ViewData [“SelectedAuthors”]參數在Book.ascx源文件的MultiSelectList函數中作為IEnumerable有問題
另一個問題是,如何使用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);
}
}
}
Store.ascx(部分視圖)用於StoreManagerController的'edit'方法
<%@ 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>
您正在使用需要綁定到作為集合的模型屬性的多選列表。 在您的情況下,您綁定到"author_id"
,它只能包含一個選定的項目ID。 您也在部分使用ViewData["authors"]
和ViewData["SelectedAuthors"]
,但在控制器操作中,不清楚這些屬性是如何填充的。
它現在已經解決了,我沒有在“edit.aspx”視圖中將“SelectedAuthors”提供給“Book.ascx”的局部視圖
<%: Html.EditorFor(model => model.Book,
new { Authors = Model.Authors, Categories = Model.Categories, SelectedAuthors = Model.SelectedAuthors }) %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.