SelectBox中选定项的Asp.net核心值是0

问题描述 投票:0回答:1

因此我设法使用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);
}
asp.net asp.net-core model-view-controller
1个回答
1
投票

我测试了您的代码,我在创建方法中更改了这部分代码:

[Bind(“ MenuItemId,Name,Description,MenuCategoryID”)

对于:

[Bind(“ MenuItemId,Name,Description,MenuCategoryId”)]

MenuCategoryId等于MenuItemViewModel类中的属性。

效果很好。

© www.soinside.com 2019 - 2024. All rights reserved.