c# - 提交后如何获取价值 - ASP.NET CORE MVC
问题描述
我无法检索 DropDownList 的值。这是我的 Create.cshtml:
@model BikeService.Models.Bike
@{
ViewData["Title"] = "Add new Bike";
}
<form method="post" asp-action="Create">
<div class="form-group row">
<div class="col-4">
<label asp-for="Customer" class=""></label>
</div>
<div class="col-8 dropdown">
@{
var options = new SelectList(@ViewBag.ListOfCustomers, "Id", "Name");
@Html.DropDownList("customers", options);
}
</div>
</div>
</div>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
DropDownList 的数据很好。
<div class="col-8 dropdown">
<select id="customers" name="customers">
<option value="3384186f-a3c4-4afe-a5be-12544a91acb7">Alex</option>
<option value="93b68f45-9c24-45e1-afc0-4549610b7c0d">John</option>
<option value="456502ca-f08f-49e6-ad90-d32be262ed58">Petter<option>
</select>
</div>
这是控制器
[HttpPost]
public async Task<IActionResult> Create(Bike bike)
{
await _bikeServices.AddBike(bike);
return View();
}
尽管下拉列表中的选项已正确分配,但在 CustomerID 值字段为空的控制器中,未发送所选值。
解决方案
当提交表单时,mvc 框架将输入元素的名称映射到模型的属性。
CustomerID
所以下拉列表名称不应该是customers
. 尝试 :
@Html.DropDownList("CustomerID", options)
现在选择元素将呈现为:
<select id="CustomerID" name="CustomerID">
<option value="3384186f-a3c4-4afe-a5be-12544a91acb7">Alex</option>
<option value="93b68f45-9c24-45e1-afc0-4549610b7c0d">John</option>
<option value="456502ca-f08f-49e6-ad90-d32be262ed58">Petter<option>
</select>
并且选定的值将回发Bike
到属性中的模型中CustomerID
。
推荐阅读
- python - 熊猫从具有值的列中选择并获取列名
- batch-file - 如何将 10 个 excel 文件移动到由批处理文件创建的 10 个不同文件夹中
- uwp - Windows iot core 发送数据到远程服务器 52.139.250.253 费用网络
- javascript - 如何从谷歌表格中获取数据作为字典数组
- sql-server - 无法在 Raspbian 10(Buster)上为 SQL Server 获取 ODBC 驱动程序 17
- c++ - 断点不会命中 CLion
- php - Codeigniter:如何在重定向中传递搜索词
- wordpress - 是否有任何用于问题和多个答案的插件或页面构建器(用于手动输入)
- c++ - C++ Stream 类打开文件失败
- python-3.x - 在单个文档中翻译多种语言的问题