因此,我设法使用SelectList(...)
和ViewData[...]
来填充选择框。这些项目显示在选择框中,我可以选择一个项目。选择框的文本是类别Name
,而 Value 是MenuCategoryID
。然后,我将链接到文本的值保存在模型的MenuCategoryId
属性中。问题是,当用户选择一个项目时,它似乎将值保存为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);
}