【问题标题】:How to filter the options of a drop down list using another drop down list如何使用另一个下拉列表过滤下拉列表的选项
【发布时间】:2012-04-24 19:12:16
【问题描述】:

我是 ASP.NET 的新手,我正在使用 ASP.Net 的 MVC 3 框架。我试图使用另一个下拉列表过滤下拉列表的选项,但我无法做到这一点。我首先尝试通过填充主要类别和子类别的列表并将它们加载到页面来做到这一点。然后将每个子类别的选项的类属性设置为其父类别。最后,从第一个下拉列表中单击父类别仅显示子子类别并隐藏其余部分(这是我以前在 java 中所做的)。但是在 ASP.Net MVC 中,html 代码是如此不同,我什至无法为下拉菜单的每个选项设置类属性,它通常为所有下拉菜单设置类,而不是为每个选项设置类。这就是我现在所拥有的 这是我的观点

<p>
@Html.LabelFor(model => model.CategoryId)
@Html.DropDownListFor(x => x.CategoryId , new SelectList(Model.Categories, "CategoryId", "CategoryName"), new { onchange= "this.form.submit();"})
</p>

<p>
@Html.LabelFor(model => model.SubCategories)
@Html.DropDownListFor(x => x.SubCategories, new SelectList(Model.SubCategories, "SubCategoryId", "SubCategoryName"), new { @class = "Category1.categoryname" })
 </p>

这是我的模特

public class TestQuestionsViewModel
{
    public string CategoryId { get; set; }
    public IEnumerable<Category> Categories { get; set; }

    public string SubCategoryId { get; set; }
    public IEnumerable<SubCategory> SubCategories { get; set; }
 }

这是我的控制器类方法

    public ActionResult Create()
    {

        var model = new TestQuestionsViewModel
        {

            Categories = resetDB.Categories.OrderBy(c => c.categoryid),
            SubCategories = resetDB.SubCategories.OrderBy(sc => sc.subcategoryid)
         };
     return View(model);
    }

我的问题是如何为每个单独的选项设置类属性。或者,如果有人对如何以不同的方式执行此操作有任何建议,我愿意接受任何解决方案。谢谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor


    【解决方案1】:

    在页面最初加载时将所有子项加载到页面上,这对我来说似乎不是一个好主意。如果您有 100 个类别并且每个类别有 200 个子类别项怎么办?您真的要加载 20000 个项目吗?

    我认为您应该采用增量加载方式。为主类别下拉菜单提供值,让用户从中选择一项。调用服务器并获取属于所选类别的子类别并将该数据加载到第二个下拉列表中。您可以使用 jQuery ajax 来做到这一点,这样用户在选择一个下拉菜单时就不会感觉到完整的页面重新加载。我就是这样做的。

    创建具有两个类别属性的 ViewModel

    public class ProductViewModel
    {
        public int ProductId { set;get;}
        public IEnumerable<SelectListItem> MainCategory { get; set; }
        public string SelectedMainCatId { get; set; }
        public IEnumerable<SelectListItem> SubCategory { get; set; }
        public string SelectedSubCatId { get; set; }
    }
    

    让您的 GET Action 方法返回这个强类型视图,其中填充了 MainCategory 的内容

    public ActionResult Edit()
    {
       var objProduct = new ProductViewModel();             
       objProduct.MainCategory = new[]
       {
          new SelectListItem { Value = "1", Text = "Perfume" },
          new SelectListItem { Value = "2", Text = "Shoe" },
          new SelectListItem { Value = "3", Text = "Shirt" }
       };
       objProduct.SubCategory = new[] { new SelectListItem { Value = "", Text = "" } };
       return View(objProduct);
    }
    

    在你的强类型视图中,

    @model MvcApplication1.Models.ProductViewModel
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    @using (Html.BeginForm())
    {    
        @Html.DropDownListFor(x => x.SelectedMainCatId, new SelectList(Model.MainCategory,"Value","Text"), "Select Main..")
        @Html.DropDownListFor(x => x.SelectedSubCatId, new SelectList(Model.SubCategory, "Value", "Text"), "Select Sub..")    
        <button type="submit">Save</button>
    }
    <script type="text/javascript">
        $(function () {
            $("#SelectedMainCatId").change(function () {
                var val = $(this).val();
                var subItems="";
                $.getJSON("@Url.Action("GetSub","Product")", {id:val} ,function (data) {
                  $.each(data,function(index,item){
                    subItems+="<option value='"+item.Value+"'>"+item.Text+"</option>"
                  });
                  $("#SelectedSubCatId").html(subItems)
                });
            });
        });
    </script>
    

    将 GetSub 操作方法添加到您的控制器以返回所选类别的子类别。我们以 Json 形式返回响应

     public ActionResult GetSub(int id)
     {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem() { Text = "Sub Item 1", Value = "1" });
        items.Add(new SelectListItem() { Text = "Sub Item 2", Value = "8"});
        // you may replace the above code with data reading from database based on the id
    
        return Json(items, JsonRequestBehavior.AllowGet);
     }
    

    现在所选值将在您的 HTTPOST 操作方法中可用

        [HttpPost]
        public ActionResult Edit(ProductViewModel model)
        {
            // You have the selected values here in the model.
            //model.SelectedMainCatId has value!
        }
    

    【讨论】:

    • 我忘了谢谢你@Shyju...这很好用,非常感谢。我用过它,效果很好。此外,它还帮助我研究了有关 Json 和 Ajax 的更多信息。
    • 请理解Edit action result中的内码
    • @Shyju 你能解释一下这行代码吗: $.getJSON("@Url.Action("GetSub","Product")", {id:val} ,function (data) as正如我所看到的,您正在调用“GetSub”方法,但“Product”是什么?
    • Product 是定义GetSub 动作方法的控制器。基本上,Url.Action 方法采用 action 方法、控制器名称和路由值,并生成 GetSub action 方法的相对 url,我们将使用它来进行 ajax 调用
    • 非常感谢@shyju,我正在寻找以下程序。非常感谢
    【解决方案2】:

    您需要添加另一种方法来处理回发并过滤子类别选项。像这样的:

    [HttpPost]
    public ActionResult Create(TestQuestionsViewModel model)
    {
        model.SubCategories = resetDB.SubCategories
                .Where(sc => sc.categoryid == model.SubCategoryId)
                .OrderBy(sc => sc.subcategoryid);
        return View(model);    
    }
    

    编辑

    顺便说一句,如果您仍然需要将类名设置为另一个下拉菜单,则不能那样做。最简单的方法是将“SelectedCategoryName”属性添加到您的模型中,并像 { @class= ModelSelectedCategoryName } 一样引用。

    【讨论】:

    • 服务器端或客户端会发生什么?
    猜你喜欢
    • 2020-10-18
    • 1970-01-01
    • 2014-09-02
    • 2018-04-16
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2015-02-07
    相关资源
    最近更新 更多