当前位置: 动力学知识库 > 问答 > 编程问答 >

dropdownlistfor - How to specify name for a dropdownlist asp.net mvc in hard coded scenario?

问题描述:

This is in my action method:

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

}

I know I can do this:

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

But the dropdownlist name would also be hardCodedList.

Here I want to specify the list name as CourseList,and I try this is in my Index view:

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

but it doesn't work:

I also know I can specify name of the list if I pass an anonymous list like this:

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

But here I want to keep the list in my action method, not in the view. How can I specify name in this case?

网友答案:

Viewbag is dynamic so try casting it.

change

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

to something like:

@Html.DropDownList("CourseList", ViewBag.hardCodedList as List<SelectListItem>, "SelectList")
分享给朋友:
您可能感兴趣的文章:
随机阅读: