我正在尝试从下拉列表中清除选定的值,但该值仍然存在。使用@Html.DropDownListFor
控制器
public class HomeController : Controller
{
[Route("/Home/Index")]
[Route("/Home/Index/{Category}")]
[Route("/Home/Index/{Category}/{Type}")]
public IActionResult Index(HomeModel model)
{
// Issue is here
// for url: home/index/accessories/test
// "Category" is cleared if it is not valid "type"
// but still "Accessories" remains selected in the drop down
if (model.Type != "Electronics" && model.Type != "Furniture")
{
model.Category = string.Empty;
}
return View(new HomeModel() { Category = model.Category, Type = model.Type });
}
查看
@model WebApplication1.Controllers.HomeModel
<select asp-for="Category" asp-items="@Model.Categories"></select>
<select asp-for="Type" asp-items="@Model.Types"></select>
模型
public class HomeModel
{
public string Category { get; set; }
public string Type { get; set; }
public List<SelectListItem> Categories { get; set; } = new List<SelectListItem>
{
new SelectListItem() { Text="Computers & Laptops", Value="Computers-Laptops" },
new SelectListItem() { Text="Accessories", Value="Accessories" },
};
public List<SelectListItem> Types { get; set; } = new List<SelectListItem>
{
new SelectListItem() { Text="Electronics", Value="Electronics" },
new SelectListItem() { Text="Furniture", Value="Furniture" },
};
}
我试图在“类别”下拉列表中添加一个空值,但仍然没有运气。
<select asp-for="Category" asp-items="@Model.Categories">
<option value="">Select Category</option>
</select>
答案 0 :(得分:5)
问题出在ModelState
之内。发生的情况是,当将URL参数绑定到视图模型时,会将值添加到模型状态字典中。渲染视图时,不仅将HomeModel
传递到视图,而且在场景下也传递ModelState
-它具有比视图模型更高的priority。因此,当您重置model.Category
时,Category
中的ModelState
键仍然具有值accessories
,这就是为什么在下拉列表中选择它的原因。
解决方案很简单,调用.Clear()
清除模型状态并使视图模型获胜:
[Route("/Home/Index")]
[Route("/Home/Index/{Category}")]
[Route("/Home/Index/{Category}/{Type}")]
public IActionResult Index(HomeModel model) {
// Issue is here
// for url: home/index/accessories/test
// "Category" is cleared if it is not valid "type"
// but still "Accessories" remains selected in the drop down
if (model.Type != "Electronics" && model.Type != "Furniture") {
model.Category = string.Empty;
}
ModelState.Clear();
return View(new HomeModel() { Category = model.Category, Type = model.Type });
}