Adding HTML Class Tag Under ≪Option≫ in Html.Dropdownlist

How to put class inside Html.Dropdownlist?

It seems you are trying to set the SelectedValue of a SelectList within the DropDownList helper which is not possible.

You have to set the SelectedValue property when you create the SelectList. See following example.

ViewBag.DropList = new SelectList(new[]{
new SelectListItem{ Text="one", Value="1"},
new SelectListItem{ Text="two", Value="2"},
new SelectListItem{ Text="three", Value="3"}
}, "Value", "Text", 2);

In the above code, I have set 2 as selected item when the SelectList is initialized. After that you can pass the SelectList and HTML attributes as below.

@Html.DropDownList("destination", (SelectList)ViewBag.DropList, new { @class = "form-control" })

Thanks!

Solution:

@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() {Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), new{@class="form-control"})

Adding a class to HTML.DropDownListFor

Four of the DropDownListFor overloads have HTML Attributes as their last parameter. This one is probably the easiest. Modifying your example, it becomes:

@Html.DropDownListFor(model => model.Business, 
new SelectList(
new List<Object>{
new { ... },
new { ... },
new { ... }
},
"value",
"text",
2),
new {
@class = "myclass"
})

Can I add html or css classes to @Html.DropDownListFor items

I couldn't get the exact answer (with the coloured box next to the text) but I was able to change the option text colour by using javascript:

<script type="text/javascript">
$(function () {
$("#cmbColour > option").each(function () {
switch(this.value)
{
case "blue":
$(this).addClass("cmbBlue");
break;
case "red":
$(this).addClass("cmbRed");
break;
case "green":
$(this).addClass("cmbGreen");
break;
case "purple":
$(this).addClass("cmbPurple");
break;
case "grey":
$(this).addClass("cmbGrey");
break;
case "yellow":
$(this).addClass("cmbYellow");
break;
}
});
});
</script>

and the CSS:

.cmbBlue {
color: #89C4F4;
}

.cmbRed {
color: #F3565D;
}

.cmbGreen {
color: #1bbc9b;
}

.cmbPurple {
color: #9b59b6;
}

.cmbGrey {
color: #95a5a6;
}

.cmbYellow {
color: #F8CB00;
}

You can change the background-color using this method but it was too busy in the UI so I went for the text colour.

I did try to use the jQuery .append to insert a div into the option, which worked but it seemed to ignore any css applied directly to it.

This is how it looks:

result

How to add class to the @Html.DropDownList?

Try this:

@Html.DropDownList(
"RoundOffInterval",
new List<SelectListItem>
{
new SelectListItem{ Text="Select Roundoff Interval",Value=""},
new SelectListItem{ Text="5",Value = "5" },
new SelectListItem{ Text="10", Value = "10" },
new SelectListItem{ Text="15", Value = "15" },
new SelectListItem{ Text="20", Value = "20" },
new SelectListItem{ Text="30", Value = "30" },
},
new {@class="select2_demo_4 form-control"})

Adding a css class to select using @Html.DropDownList()

Looking at the controller, and learing a bit more about how MVC actually works, I was able to make sense of this.

My view was one of the auto-generated ones, and contained this line of code:

@Html.DropDownList("PriorityID", string.Empty)

To add html attributes, I needed to do something like this:

@Html.DropDownList("PriorityID", (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class="dropdown" })

Thanks again to @Laurent for your help, I realise the question wasn't as clear as it could have been...

UPDATE:

A better way of doing this would be to use DropDownListFor where possible, that way you don't rely on a magic string for the name attribute

@Html.DropDownListFor(x => x.PriorityID, (IEnumerable<SelectListItem>)ViewBag.PriorityID, new { @class = "dropdown" })

Html helper method for DropDownList to add title tag for each list items

You will need to create on your own.

You can pull from similar implementation
Adding html class tag under <option> in Html.DropDownList

Also
give a try to

@Html.DropDownListFor(model => model.priority, new SelectList(ViewBag.Priority, "Value", "Text"), "-- Select Priority --", new { @class = "required", title="priority" })

Can we add class attribute in option element?

Yes it is valid.

From the W3Schools website:

The <option> tag also supports the Global Attributes in HTML.

From which the class attribute is a part of. Please note that often, the option tag has formatting issues regarding the browser you are using, so styling it can be a little tricky.

EDIT: Since I wrote this answer, it has come to my attention that W3Schools probably isn't the most reliable source of good information. The previous answer isn't at all wrong, but it came from a source that has proven to be somewhat inconsistent/incomplete. As such, I think I should also append a more official link to this subject here.

CSS Class for DropDownListFor

The third parameter already is the htmlAttributes field, so your syntax is wrong. This is what you're after:

@Html.DropDownListFor(model => model.OrderItemTypeId, 
(SelectList)ViewBag.OrderItemTypes,
new { @class = "form-control etc" })

See Microsoft Docs.

Is it possible to include HTML elements in a dropdown list?

Here is an example of how you could do it by building your own drop down handler.

CSS

.select {
width: 10em;
height: 1em;
border-style: solid;
border-width: 1px;
border-radius: 3px;
z-index: 0;
}
.gradient1 {
background-color: #ebebeb;
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#ebebeb), to(#999999));
background-image: -webkit-linear-gradient(top, #ebebeb, #999999);
background-image: -moz-linear-gradient(top, #ebebeb, #999999);
background-image: -ms-linear-gradient(top, #ebebeb, #999999);
background-image: -o-linear-gradient(top, #ebebeb, #999999);
}
.gradient2 {
background-color: #999999;
background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#ebebeb), to(#ebebeb));
background-image: -webkit-linear-gradient(top, #999999, #ebebeb);
background-image: -moz-linear-gradient(top, #999999, #ebebeb);
background-image: -ms-linear-gradient(top, #999999, #ebebeb);
background-image: -o-linear-gradient(top, #999999, #ebebeb);
}
.list {
position: relative;
margin-left: -1px;
padding: 0% 0% 0% 1px;
width: 100%;
height: auto;
box-shadow: 0px 5px 10px #888888;
border-style: solid;
border-width: 1px;
border-radius: 3px;
background-color: #ebebeb;
display: none;
margin-top: -4px;
z-index: 2;
}
.option {
display: block;
list-style-type: none;
text-align: left;
}
.option:hover {
background-color: blue;
}
.arrowDown {
position: relative;
top: -50%;
left: 90%;
width: 0%;
height: 0%;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 6px solid #444;
}
.value {
position: relative;
top: -2px;
left: 0%;
width: 100%;
height: 100%;
z-index: 1;
}

HTML

<div>
<div id="first" class="select">
<div class="value"></div>
<div class="arrowDown"></div>
<ul class="list">
<li class="option"><b>one</b></li>
<li class="option"><strike>two</strike></li>
<li class="option"><em>three</em></li>
</ul>
</div>
<div id="second" class="select">
<div class="value"></div>
<div class="arrowDown"></div>
<ul class="list">
<li class="option"><b>four</b></li>
<li class="option"><strike>five</strike></li>
<li class="option"><em>six</em></li>
</ul>
</div>
<div id="third" class="select">
<div class="value"></div>
<div class="arrowDown"></div>
<ul class="list">
<li class="option"><b>seven</b></li>
<li class="option"><strike>eight</strike></li>
<li class="option"><em>nine</em></li>
</ul>
</div>
<button id="getValue1">Get Text value 1</button>
<button id="getValue2">Get HTML value 2</button>
<button id="getValue3">Get Text value 3</button>
</div>

Javascript

(function (global) {
global.addEventListener("load", function onLoad() {
global.removeEventListener("load", onLoad);

var selects = document.getElementsByClassName("select");

function getTextValue(selectId) {
var select = document.getElementById(selectId),
values,
text = "";

if (select) {
values = select.getElementsByClassName("value");
if (values && values.length) {
text = values[0].textContent;
}
}

return text;
}

function getHTMLValue(selectId) {
var select = document.getElementById(selectId),
values,
html = "";

if (select) {
values = select.getElementsByClassName("value");
if (values && values.length) {
html = values[0].innerHTML;
}
}

return html;
}

function hideAll(not) {
Array.prototype.forEach.call(selects, function (select) {
if (select !== not) {
Array.prototype.forEach.call(select.getElementsByClassName("list"), function (ul) {
ul.style.display = "none";
});

select.className = (select.className.replace(/gradient[12]/, "").trim() + " gradient1").trim();
}
});
}

document.addEventListener("click", hideAll, false);

Array.prototype.forEach.call(selects, function (select) {
select.className = (select.className.trim() + " gradient1").trim();

var lists = select.getElementsByClassName("list"),
options,
values,
value;

if (lists && lists.length) {
options = lists[0].getElementsByClassName("option");
if (options && options.length) {
values = select.getElementsByClassName("value");
if (values && values.length) {
value = values[0];
value.innerHTML = options[0].innerHTML;

Array.prototype.forEach.call(options, function (option) {
option.addEventListener("click", function clickOption() {
value.innerHTML = this.innerHTML;
}, false);
});
}
}
}

select.addEventListener("click", function clickSelect(evt) {
evt.stopPropagation();
hideAll(this)

var lists = this.getElementsByClassName("list"),
list;

if (lists && lists.length) {
list = lists[0];

if (global.getComputedStyle(list).display === "none") {
list.style.display = "block";
} else {
list.style.display = "none";
}
}

if (this.className.indexOf("gradient1") !== -1) {
this.className = this.className.replace("gradient1", "gradient2");
} else {
this.className = (this.className.replace(/gradient\d/, "").trim() + " gradient1").trim();
}
}, false);
});

document.getElementById("getValue1").addEventListener("click", function () {
console.log(getTextValue("first"));
}, false);

document.getElementById("getValue2").addEventListener("click", function () {
console.log(getHTMLValue("second"));
}, false);

document.getElementById("getValue3").addEventListener("click", function () {
console.log(getTextValue("third"));
}, false);
}, false);
}(window));

On jsfiddle



Related Topics



Leave a reply



Submit