【问题标题】:How to get value from Dropdownlist?如何从下拉列表中获取价值?
【发布时间】:2020-08-11 21:17:56
【问题描述】:

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

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

【问题讨论】:

  • 添加关于控制器和视图的代码
  • @HienNguyen 好的,我已经编辑了我的问题..
  • 您希望根据您选择的值对您的数据库进行更新操作,您可以展示一下吗?
  • @SalahAkbari 现在我只想在类别下拉列表中选择值时,子类别下拉列表被填充。
  • 如果将@Html.DropDownList("Category" 更改为@Html.DropDownList("CategoryId" 会发生什么?它们需要相同才能使 Model Binder 按预期工作,

标签: c# asp.net-mvc


【解决方案1】:

你需要处理下拉菜单的变化

 @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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    相关资源
    最近更新 更多