将DropDownList值获取到POST方法中

时间:2019-12-17 01:19:07

标签: drop-down-menu asp.net-core-mvc http-post

我正在这个ASP.NET Core MVC上工作,这里有这个DropDownLisit,它使用ControllerViewBag.DishTypes获取其值。但是,提交表单后,POST方法未获得在DropDownList中选择的选项的值。代码段如下:

控制器:GET方法

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

ViewBag.DishTypes = allDishTypes;

return View();

查看

<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方法

[HttpPost]
public IActionResult AddMenuItems([Bind("DishTypeId, DishName, Cost")] Dishes dishesObj)
{
    ....
}

1 个答案:

答案 0 :(得分:0)

  

POST方法未获取DropDownList中选择的选项的值

请注意,您在代码中指定了name=dishtype。这样,字段名称是 始终与此name属性相同,即由dishtype代替DishTypeId,默认情况下,ASP.NET Core不会识别该属性。

要解决此问题,只需删除该属性,以使其使用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>
相关问题