首页 > 解决方案 > 如何从下拉列表中获取价值?

问题描述

我有两个DropDownList通过外键相互关联。类别和子类别(categoryid作为外键)。我正在从数据库中检索类别并将它们填充为: DB CLASS

public class DB
 {
     public static List<SelectListItem> Categories {
              get{
                   List<SelectListItem> list = new List<SelectListItem {
                    new SelectListItem{Text = "Category1" , Value = "categoryId1"},
                    new SelectListItem{Text = "Category2" , Value = "categoryId2"}
                 };
        return list;
     }
    public static List<SelectListItem> SubcategoryWithCategoryId(int categoryId)
    {...}
 }

现在我可以使用期望 categoryId 作为输入的方法填充子类别下拉列表:
查看

 @Html.DropDownList("Category", DB.Categories, "Select Category", new { style = "width:80px" })

 @Html.DropDownList("Subcategory", DB.SubcategoryWithCategoryId(categoryId), "Select Subcategory", new { style = "width:80px" })

我是ASP.NET MVC的初学者,我正在使用ADO.NET访问数据库。我现在如何获取选定项目的值字段,以便我可以将其放入我DB.SubcategoryWithCategoryId(categoryId)的检索跨选定类别映射的子类别?

控制器

public ActionResult Index()
        {
            return View();
        }

标签: c#asp.net-mvc

解决方案


您需要将下拉菜单的 onchange 处理为

 @Html.DropDownList("Category", DB.Categories, "Select Category", new { style = "width:80px", 
onchange = "location.href='@Url.Action("Index", "Controller", new { category= "yourcategory"})'" })

并添加类别作为索引操作的参数

public ActionResult Index(string category)

推荐阅读