Drop down menu 在POST方法中获取DropDownList值

Drop down menu 在POST方法中获取DropDownList值,drop-down-menu,asp.net-core-mvc,http-post,Drop Down Menu,Asp.net Core Mvc,Http Post,我正在开发这个ASP.NET核心MVC,其中我有一个DropDownList,它使用ViewBag.DishTypes从Controller获取其值。但是,在提交表单时,POST方法不会获取在DropDownList中选择的选项的值。代码片段如下所示: 控制器:获取方法 var allDishTypes = _context.DishType .ToList() .Select(dt => new SelectListItem { Value = dt.DishTypeId

我正在开发这个
ASP.NET核心MVC
,其中我有一个
DropDownList
,它使用
ViewBag.DishTypes
Controller
获取其值。但是,在提交表单时,
POST
方法不会获取在
DropDownList
中选择的选项的值。代码片段如下所示:

控制器:获取方法

var allDishTypes = _context.DishType
    .ToList()
    .Select(dt => new SelectListItem { Value = dt.DishTypeId.ToString(), Text = dt.DishTypeName.ToString() }).ToList();

ViewBag.DishTypes = allDishTypes;

return View();
[HttpPost]
public IActionResult AddMenuItems([Bind("DishTypeId, DishName, Cost")] Dishes dishesObj)
{
    ....
}
查看

<form asp-controller="Home" asp-action="AddMenuItems">
    <div class="row">
        <label class="my-1 mr-2" for="inlineFormCustomSelectPref">Dish Type</label>
        <div class="input-group">
            <div class="fg-line form-chose">
                <label asp-for="DishTypeId" class="fg-labels" for="DishTypeId">Dish Type</label>
                <select asp-for="DishTypeId" asp-items="ViewBag.DishTypes" class="form-control chosen" data-placeholder="Choose Dish Type" required name="dishtype" id="dishtype">
                    <option value=""></option>
                </select>
             </div>
         </div>
    ....
POST方法未获取DropDownList中所选选项的值

请注意,您在代码中指定了一个
name=dishtype
。通过这种方式,字段名是 始终与此
name
属性相同,即
dishtype
而不是
DishTypeId
,默认情况下,ASP.NET核心不会识别该属性

要解决该问题,只需删除该属性,使其使用
asp for
自动生成
name
属性:

<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes" class="form-control chosen" data-placeholder="Choose Dish Type" required name="dishtype" id="dishtype" > <option value=""></option> </select>