代码之家  ›  专栏  ›  技术社区  ›  Sunny

下拉选择未被清除

  •  0
  • Sunny  · 技术社区  · 7 年前

    我试图从下拉列表中清除所选的值,但该值仍然存在。这是同样的行为使用 @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>
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   JLe    7 年前

    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 });
    }