![](/img/trans.png)
[英]Why does my List of Objects rendered as Checkboxes return an Empty List? [ASP.NET Core - 3.1]
[英]ASP.Net Core 3.1 MVC - MultiSelect with List of Objects
所以,基本上目标是:
用户从选择列表中为一本书(流派)选择多个“类别”。 一些例子是:
在用户选择 1 个或多个(多个)后,他们将图书保存到数据库中。
功能方面,当我处理单一类型时一切正常(类型保存为单个字符串),但我需要支持多种类型。
我做的第一件事只是将string Category
更改为List<string> Categories
,但这导致了此处看到的错误: StackOverflow 问题已解决我尝试了“TuPack”提供的解决方案,并且该错误消失了...但这导致了一个全新的问题。
您已经了解我现在的情况:为了从我的<select></select>
获得任何结果,我必须这样做:
<select asp-for="CategoryIds[0].CategoryId" asp-items="ViewBag.Language"
class="form-control" multiple="multiple">
<option value="">Please choose book language</option>
</select>
这当然有效.. 用于获取用户选择的第一个类别。 仅此而已。
至于到目前为止的代码,相关性明智......我会切断与数据库相关的东西,因为问题早在那里之前就发生了:
控制器:
public async Task<ViewResult> AddNewBookAsync(bool isSuccess = false, int bookId = 0)
{
var model = new BookModel();
ViewBag.Language = new SelectList(await _languageRepository.GetLanguages(), "Id", "Name");
ViewBag.IsSucess = isSuccess;
ViewBag.BookId = bookId;
return View(model);
}
[HttpPost]
public async Task<IActionResult> AddNewBook(BookModel bookModel)
{
if (ModelState.IsValid)
{
int id = await _bookRepository.AddNewBook(bookModel);
if(id > 0)
{
return RedirectToAction(nameof(AddNewBook), new { isSuccess = true, bookId = true });
}
}
ViewBag.Language = new SelectList(await _languageRepository.GetLanguages(), "Id", "Name");
return View();
}
书型:
public class BookModel
{
public int Id { get; set; }
[StringLength(100, MinimumLength = 5)]
[Required(ErrorMessage ="Please enter the title of your book")]
public string Title { get; set; }
[Required(ErrorMessage = "Please enter the author's name")]
public string Author { get; set; }
[StringLength(500)]
public string Description { get; set; }
[Required(ErrorMessage = "Please choose the language of your book")]
public string Language { get; set; }
[Display(Name = "Genre")]
public List<Categories> CategoryIds { get; set; } = new List<Categories>();
[Required(ErrorMessage = "Please enter the total pages")]
[Display(Name = "Total pages of book")]
public int? TotalPages { get; set; }
}
之前展示过相关的Html代码,不再贴出。
类别 ID 1 是“动作和冒险”。
顺便说一句,我相信这很容易分辨,但这只是一个“实践项目”。 我不想在不知道自己在做什么的情况下对我正在从事的主要项目进行重大更改。
更新
我曾经将IList<SelectListItem>
属性添加到Book
模型并在CategoryIds
属性中存储多个类别。 它对我有效。
控制人代码
public IList<SelectListItem> GetCategories()
{
var categories = new List<Category>
{
new Category {Id = 1, CategoryName = "Action and Adventure"},
new Category {Id = 2, CategoryName = "Classics"},
new Category {Id = 3, CategoryName = "Comic Book or Graphic Novel"},
}; // here you can load categories from DB, this is only for test
var categoryListItem = categories
.Select(x => new SelectListItem { Text = x.CategoryName, Value = x.Id.ToString() })
.ToList();
return categoryListItem;
}
[Route("/books/add")]
public IActionResult _AddNewBooks()
{
var model = new BookModel { CategoryList = GetCategories() };
return View(model);
}
[Route("/books/addnewbook")]
[HttpPost]
public IActionResult AddNewBook(BookModel model)
{
if (ModelState.IsValid)
{
//int id = await _bookRepository.AddNewBook(bookModel);
//if (id > 0)
//{
// return RedirectToAction(nameof(AddNewBook), new { isSuccess = true, bookId = true });
//}
}
//ViewBag.Language = new SelectList(await _languageRepository.GetLanguages(), "Id", "Name");
model.CategoryList = GetCategories();
return View();
}
型号代码
public class BookModel
{
public int Id { get; set; }
public string Title { get; set; }
public IList<SelectListItem> CategoryList { get; set; }
[Required(ErrorMessage = "Please select at last 1 Category")]
public List<int> CategoryIds { get; set; }
public BookModel(){
CategoryList = new List<SelectListItem>();
}
}
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
}
视图代码
<select asp-for="CategoryIds" asp-items="Model.CategoryList"
placeholder="Select Categories"
onchange="console.log($(this).children(':selected').length)"
class="search-box form-control">
</select>
1>您正在使用ViewBag.Language
作为Category
项目。 我建议您将Categories
返回到视图。
2> asp-for
应该是CategoryIds
。
<select asp-for="CategoryIds" asp-items="ViewBag.Language" class="form-control" multiple="multiple"> <option value="">Please choose book language</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.