Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.DropDownList - How to add extra <option> to list

I am using Html.DropDownList to create an options list like so

Html.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?

like image 726
Chris Avatar asked Mar 08 '12 09:03

Chris


People also ask

How do you add a value to a drop-down list in HTML?

The add() method is used to add an option to a drop-down list.

How do you make a dropdown in HTML and CSS?

Example Explained HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button> element. Use a container element (like <div>) to create the dropdown content and add whatever you want inside of it. Wrap a <div> element around the elements to position the dropdown content correctly with CSS.


2 Answers

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.

like image 121
Mohammed Swillam Avatar answered Nov 10 '22 01:11

Mohammed Swillam


I tried to do this before and end with using jQuery:

$("#LogType").append($("<option />").val("0").html("-- All --"));
like image 41
Simon Wang Avatar answered Nov 09 '22 23:11

Simon Wang