It's not possible to use Razor's @Html.DropDownList()
method to create the Bootstrap dropdown you've mentioned. Though it's easy enough to create your own HTML helper that renders the code necessary to create the aforementioned dropdown.
There are plenty of tutorials and guides (such as this one) that will take you through the process of creating a custom HTML Helper. They're really not that difficult to create and can really help speed up your development times and encourage code reuse.
Update:
Given the amount of attention this question is getting an the number of upvotes the (incorrect) answer below is getting, here is a long overdue (year and a half!) code sample with an image to demonstrate the differences.
You can copy and paste this code into your solution and it should work.
The code:
public class BootstrapHtml
{
public static MvcHtmlString Dropdown(string id, List<SelectListItem> selectListItems, string label)
{
var button = new TagBuilder("button")
{
Attributes =
{
{"id", id},
{"type", "button"},
{"data-toggle", "dropdown"}
}
};
button.AddCssClass("btn");
button.AddCssClass("btn-default");
button.AddCssClass("dropdown-toggle");
button.SetInnerText(label);
button.InnerHtml += " " + BuildCaret();
var wrapper = new TagBuilder("div");
wrapper.AddCssClass("dropdown");
wrapper.InnerHtml += button;
wrapper.InnerHtml += BuildDropdown(id, selectListItems);
return new MvcHtmlString(wrapper.ToString());
}
private static string BuildCaret()
{
var caret = new TagBuilder("span");
caret.AddCssClass("caret");
return caret.ToString();
}
private static string BuildDropdown(string id, IEnumerable<SelectListItem> items)
{
var list = new TagBuilder("ul")
{
Attributes =
{
{"class", "dropdown-menu"},
{"role", "menu"},
{"aria-labelledby", id}
}
};
var listItem = new TagBuilder("li");
listItem.Attributes.Add("role", "presentation");
items.ForEach(x => list.InnerHtml += "<li role=\"presentation\">" + BuildListRow(x) + "</li>");
return list.ToString();
}
private static string BuildListRow(SelectListItem item)
{
var anchor = new TagBuilder("a")
{
Attributes =
{
{"role", "menuitem"},
{"tabindex", "-1"},
{"href", item.Value}
}
};
anchor.SetInnerText(item.Text);
return anchor.ToString();
}
}
Usage:
@using (Html.BeginForm("", "", FormMethod.Post))
{
var items = new List<SelectListItem>()
{
new SelectListItem() { Text = "Item 1", Value = "#" },
new SelectListItem() { Text = "Item 2", Value = "#" },
};
<div class="form-group">
@Html.Label("Before", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("Name", items, "Dropdown", new { @class = "form-control"})
</div>
</div>
<br/>
<br/>
<br/>
<div class="form-group">
@Html.Label("After", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@BootstrapHtml.Dropdown("dropdownMenu1", items, "Dropdown")
</div>
</div>
}