首页 > 解决方案 > 提交后如何获取价值 - 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 值字段为空的控制器中,未发送所选值。

从表单发送到控制器的对象

标签: c#asp.netasp.net-mvc

解决方案


当提交表单时,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


推荐阅读