简体   繁体   中英

Setting unique id for each element in a dropdownlistfor (MVC)

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

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM