Html.DropDownList - How to add extra <option> to list
Solution 1
I'm not sure but, why don't you construct the list just before your @html.DropDownList
var myList = new SelectList(Model.LogTypeList, "ID", "Name", Model.SelectedLogType);
and then append your desired item to it.
var myList.add(new selectItem("-- ALL --",0));
and finally pass it to your syntax and see what this will result
Html.DropDownList("LogType",myList);
sorry, this is a quick answer using my iPhone, not sure if it will fix your problem, but I tried to help as much as I could.
Solution 2
I tried to do this before and end with using jQuery:
$("#LogType").append($("<option />").val("0").html("-- All --"));
Solution 3
Just for a different approach, I was amazed at how many answers on forums there were for this same question, all of which seemed overly complex for what can be achieved easily in WebForms with AppendDataItems (granted, it is webforms!).
This worked well for me a few moments ago, keeping everything inline and keeping the view and model concerns separate:
@Html.DropDownListFor(model => model.Operators,
new SelectList(new[] {
new {id=-1, name="Please select an operator"}}
.Union(Model.Operators
.Select( o=> new { id=o.Id, name=o.Name})
), "id", "name"))
Which renders out as :
<select id="Operators" name="Operators">
<option value="-1">Please select an operator</option>
<option value="1">Tony Bolton</option>
<option value="2">Joe Bloggs</option>
</select>
Haven't checked performance etc though, but felt it was worth sharing.
Chris
Updated on July 09, 2022Comments
-
Chris almost 2 years
I am using
Html.DropDownList
to create an options list like soHtml.DropDownList("LogType", new SelectList(Model.LogTypeList, "ID", "Name", Model.SelectedLogType),"-- ALL --");
As you can see I pass in a list but also pass in an extra argument to add an additional option:
"-- All --"
. The result is as follows:<select name="LogType" id="LogType"> <option value="">-- ALL -- </option> <option value="1">Debug</option> <option value="2" selected="selected">Error</option> </select>
How do I give
-- All --
an value of 0 without having to manually construct the drop down list myself?