ModelState
. 当URL参数绑定到视图模型时,会将这些值添加到模型状态字典中。渲染视图时,不仅
HomeModel
传递到视图,但在场景下面
模型状态
也通过了考试,而且考试成绩更高
priority
而不是视图模型。所以当你重置
model.Category
这个
Category
输入
还是有价值的
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 });
}