因此我设法使用SelectList(...)
和ViewData[...]
填充选择框。这些项目显示在选择框中,我可以选择一个项目。选择框的文本是类别Name
,而值是MenuCategoryID
。然后,我将链接到文本的值保存在模型的MenuCategoryId
property中。问题是,当用户选择一个项目时,它似乎将值保存为0,然后将其在模型中传递给控制器中的发布请求。模型中的其他所有值都正确无误,只是从选择框中检索到的值。
这是我的GET请求:
public async Task<IActionResult> Create()
{
List<MenuCategoryViewModel> Categories = await _Context.MenuCategories.ToListAsync();
ViewData["Categories"] = new SelectList(Categories, "MenuCategoryId", "Name");
return View();
}
这是我的SelectBox:
<select asp-for="MenuCategoryId" class="form-control" asp-items="ViewBag.Categories"></select>
这是我的MenuCategoryId
属性:
[Required]
public int MenuCategoryId { get; set; }
这是我的POST请求:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("MenuItemId,Name,Description,MenuCategoryID")] MenuItemViewModel menuItem)
{
if (ModelState.IsValid)
{
_Context.Add(menuItem);
await _Context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(menuItem);
}
我测试了您的代码,我在创建方法中更改了这部分代码:
[Bind(“ MenuItemId,Name,Description,MenuCategoryID”)
对于:
[Bind(“ MenuItemId,Name,Description,MenuCategoryId”)]
MenuCategoryId等于MenuItemViewModel类中的属性。
效果很好。