Reputation: 547
I can't seem to figure out how to set a unique ID for each element in a SelectList
(using @Html.DropDownListFor
). The div in view looks like this currently:
<div id="Courses">
@Html.DropDownListFor(c => c.Courses, new SelectList(Model.Courses, "CourseID", "Name"), "Choose Course", new { id = "courseDropDown", @class = "form-control input-sm", data_width = "100%" })
</div>
Inspecting the element in the browser shows that each element has the courseID
as a value, what I would like is for each element to have this courseID as a unique id. FYI Model.Courses
contains an enumerable of all my courses.
For the sake of completeness the reason I want this is that I have a highChart in a partial view which corresponds to the dropdownlist, and I have a button from my course page which redirects to the view with the partial div on it and loads the chart for a given course (using the ID from the coursepage). This works fine, but I just now need the dropdownlist
to display the name of that course upon page load, whereas now it simply says 'Choose Phishing Campaign'
Any help or advice is appreciated.
edit: Thanks for tidying the code up Rory
Upvotes: 2
Views: 648
Reputation: 15154
teo van kot's answer is correct (+1).
Though if you dont need to bind the CourseId for a post. you could use the SelectList
constructor:-
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
Object selectedValue
)
like so:-
<div id="Courses">
@Html.DropDownListFor(c => c.Courses, new SelectList(Model.Courses, "CourseID", "Name", "COURSEID"), "Choose Course", new { id = "courseDropDown", @class = "form-control input-sm", data_width = "100%" })
</div>
Upvotes: 1
Reputation: 389
Within the Model or controller, where you are populating the Course property you set the CourseId as a unique number.
Really it matters on the way your setting the property?
foreach(var course in DataSource.CourseTitles)
viewModel.Courses.Add(new Course(){ CourseId = i++, Name = course})
Upvotes: 1
Reputation: 12491
If you need to set default value of select
you should set some kind of CourseId
property of model in your controller and then in your View:
@Html.DropDownListFor(c => c.CourseId, new SelectList(Model.Courses, "CourseID", "Name"), "Choose Course", new { id = "courseDropDown", @class = "form-control input-sm", data_width = "100%" })
DropDownListFor
helper set this value selected on page load.
Upvotes: 2