我正在这个ASP.NET Core MVC
上工作,这里有这个DropDownLisit
,它使用Controller
从ViewBag.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)
{
....
}
答案 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" requiredname="dishtype"id="dishtype" > <option value=""></option> </select>