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