簡體   English   中英

選擇標簽助手以在下拉列表中顯示2個字段

[英]Select Tag Helper to Display 2 Fields in the Drop Down List

使用標准腳手架僅在相關表的下拉列表中顯示索引。 如何顯示多個字段,以便下拉列表有意義?

我試圖使用Shyju在“使用實體框架從數據庫表中獲取數據”一節中概述的解決方案。 在ASP.NET Core MVC中選擇Tag Helper )。

我在模型中有2個類(帶有相關作者的書籍):

namespace SimpleAppwithTwoTables.Data
{
    public class Book
    {
        public int BookID { get; set; }
        [StringLength(255)]
        [Display(Name ="Book Title")]
        public string Title { get; set; }
        public int AuthorID { get; set; }
        public Author Author { get; set; }
     }
}

namespace SimpleAppwithTwoTables.Data
{
    public class Author
    {
        public int AuthorID { get; set; }
        [Display(Name = "First Name")]
        [StringLength(50)]
        public string FirstName { get; set; }
        [Display(Name = "Last Name")]
        [StringLength(50)]
        public string LastName { get; set; }
        public ICollection<Book> Books { get; set; } = new List<Book>();
    }
}

BooksController有一個Create()方法,類似於Shyju的帖子中所述。

 public IActionResult Create()
            Author vm = new Author();
            vm.Books = _context.Book.Select(a => new SelectListItem()
            { Value = a.AuthorID.ToString(), Text = a.Author.LastName }).ToList();
            return View(vm);
        }

控制器中的這一行

 vm.Books = _context.Book.Select(a => new SelectListItem()
            { Value = a.AuthorID.ToString(), Text = a.Author.LastName }).ToList();

產生此錯誤:

“無法將類型'System.Collections.Generic.List <Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'隱式轉換為'System.Collections.Generic.ICollection <SimpleAppwithTwoTables.Data.Book>'。存在顯式轉換(您是缺少演員表?)。

請注意,我是C#的新手,並且了解這是類型轉換問題,並且出現錯誤的行期望Author模型包含ICollection <>。

我正在尋找vm.books行中所需的代碼,該代碼不進行類型轉換並且可以與ICollection一起使用。

您試圖將SelectListItem列表填充到定義為Book列表的屬性中。 SelectListItem很明顯與Book ,所以它失敗了。

一個簡單的解決方案是,您需要在視圖模型上有一個專門用於保存選擇列表選項的屬性:

public IEnumerable<SelectListItem> AuthorOptions { get; set; }

您還需要一些東西來將選擇項綁定到原始類型,而不是實際的Author實例:

public List<int> SelectedAuthorIds { get; set; }

在您看來,然后:

<select asp-for="SelectedAuthorIds" asp-items="AuthorOptions">

在發布后,如果您需要將其與一本書或其他內容相關聯,則需要使用該ID集合來查詢實際的作者對象:

var selectAuthors = await _context.Authors.Where(x => vm.SelectedAuthorIds.Contains(x.Id)).ToListAsync();

我遵循了Chris Pratt提供的建議。 花了一段時間才弄清楚,但幾乎可以正常工作了。 請參閱下面的詳細信息。

請參見上面的書籍和作者模型。

創建了一個新的ViewModel:

namespace SimpleDropDownList.Models
{
    [NotMapped]
    public class AuthorViewModel
    {
        //Property to hold the list of authors in the GET
        public IEnumerable<SelectListItem> AuthorOptions { get; set; }

        //Property to bind the selected author used in the POST
        public List<int> SelectedAuthorIds { get; set; }
    }
}

將BooksController上的Create()方法更改為:

 public IActionResult Create()
        {
            //ViewData["AuthorID"] = new SelectList(_context.Set<Author>(), "AuthorID", "AuthorID");
            AuthorViewModel vm = new AuthorViewModel();
            vm.AuthorOptions = _context.Book.Select(x => new SelectListItem()
            { Value = x.AuthorID.ToString(), Text = x.Author.LastName }).ToList();
        return View(vm);
        }

將創建視圖更改為:

 @model SimpleDropDownList.Models.Book @{ ViewData["Title"] = "Create"; } <h1>Create</h1> <h4>Book</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Title" class="control-label"></label> <input asp-for="Title" class="form-control" /> <span asp-validation-for="Title" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="AuthorID" class="control-label"></label> @*<select asp-for="AuthorID" class ="form-control" asp-items="ViewBag.AuthorID"></select>*@ <select asp-for="@Model.AuthorViewModel.SelectedAuthorIds" asp-items="@Model.AuthorViewModel.AuthorOptions"></select> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } Model: AuthorViewModel 

當我運行此程序並單擊“創建”按鈕時,將產生以下錯誤:

處理請求時發生未處理的異常。 InvalidOperationException:傳遞到ViewDataDictionary的模型項的類型為'SimpleDropDownList.Models.AuthorViewModel',但是此ViewDataDictionary實例需要一個類型為'SimpleDropDownList.Models.Book'的模型項。

我將這個問題標記為已完成,並為上述問題創建了一個新問題。 參見此處: 打開“剃刀”頁面並具有相關的下拉列表時出錯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM