【问题标题】:How to specify name for a dropdownlist asp.net mvc in hard coded scenario?如何在硬编码场景中为下拉列表 asp.net mvc 指定名称?
【发布时间】:2023-03-05 00:34:01
【问题描述】:

这是我的操作方法:

  public ActionResult Index()
        {
            List<SelectListItem> Courses = new List<SelectListItem>();
            Courses.Add(new SelectListItem{Text="Math", Value = "1"});
            Courses.Add(new SelectListItem { Text = "Science", Value = "2"});
            Courses.Add(new SelectListItem{Text="Literature", Value = "3"});
            ViewBag.hardCodedList = Courses;
            return View();
        }

我知道我可以做到:

@Html.DropDownList("hardCodedList", "SelectList")

但下拉列表名称也将是 hardCodedList。

这里我想将列表名称指定为 CourseList,我尝试在我的索引视图中:

@Html.DropDownList("CourseList", ViewBag.hardCodedList, "SelectList")

但它不起作用:

我也知道如果我传递这样的匿名列表,我可以指定列表的名称:

  @Html.DropDownList("CourseList", new List<SelectListItem>
        {
        new SelectListItem { Text = "IT", Value = "1", Selected=true},
        new SelectListItem { Text = "HR", Value = "2"},
        new SelectListItem { Text = "Finance", Value = "3"}
        }, "SelectList")

但在这里我想将列表保留在我的操作方法中,而不是在视图中。在这种情况下如何指定名称?

【问题讨论】:

    标签: asp.net-mvc dropdownlistfor selectlistitem


    【解决方案1】:

    Viewbag 是动态的,因此请尝试投射它。

    改变

    @Html.DropDownList("CourseList", ViewBag.hardCodedList, "SelectList")
    

    类似于:

    @Html.DropDownList("CourseList", ViewBag.hardCodedList as List<SelectListItem>, "SelectList")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多