我正在尝试将多个单选列表绑定到我的视图模型中的一个字符串列表中,我具有以下属性:public List<string> Items {get; set;}
,并且在我的视图中,我具有3个带有单选选项的选择列表,但是当我尝试对模型进行绑定时我的选择列表使用asp-for="@Model.Items"
的Items属性转换为多选择列表。为什么?
我的看法:
<form asp-controller="Admin" asp-action="Index" method="post">
<div class="col-12">
<div class="row">
<div class="form-group col-4">
<div class="d-inline-block">
<label>Order By Price:</label>
</div>
<div class="d-inline-block">
<select class="form-control" asp-for="@Model.Items" style="width:150px">
<option value="Ascending">Ascending</option>
<option value="Descending">Descending</option>
</select>
</div>
</div>
<div class="form-group col-4">
<div class="d-inline-block">
<label>Order By Name:</label>
</div>
<div class="d-inline-block">
<select class="form-control" asp-for="@Model.Items" style="width:150px">
<option value="A-Z">A-Z</option>
<option value="Z-A">Z-A</option>
</select>
</div>
</div>
<div class="form-group">
<div class="d-inline-block">
<button type="submit" class="btn btn-secondary">Confirm</button>
</div>
</div>
</div>
</div>
</form>
控制器:
[HttpPost]
public IActionResult Index(MangeProductsViewModel vm)
{
return View(new MangeProductsViewModel
{
Products = productRepository.Products.ToList().SortProducts(vm)
});
}
我的视图模型
public IEnumerable<Product> Products { get; set; }
public List<string> Items { get; set; }
当我从列表中选择项目时,它可以正确添加它们,问题是用户可以从一个列表中选择多个选项
这是因为asp-for
会调用标签帮助程序,并且对于类型为List<string>
的道具,所生成的HTML将是一个选择倍数。但是,这对您<< anyways>都不起作用,因为它将为所有选择提供相同的名称。结果,它们将彼此简单地覆盖,而不是彼此相加。为此,您将不得不通过以下方式手动处理:
<select name="Items[]">
@foreach (var option in Model.SelectList1Options)
{
<option value="@option.Value">@option.Text</option>
}
</select>
对于每个下拉列表。