给出以下MVC剃刀代码,它从列表中创建一个下拉列表:
@Html.DropDownList("MyTestList",null,new { @class = "btn btn-default dropdown-toggle" })
这将创建以下下拉列表:
当使用getbootstrap.com的代码时:
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1"> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">test1</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">test2</a></li> </ul> </div>
它会显示如下的下拉列表:
题:
当使用@ Html.DropDownList作为使用MVC的HTML代码时,是否可以得到相同的外观?
解决方法
不可能使用Razor的@ Html.DropDownList()方法创建您提到的Bootstrap下拉列表。虽然很容易创建自己的HTML帮助程序,使代码需要创建上述的下拉列表。
有很多教程和指南(such as this one)将引导您完成创建自定义HTML助手的过程。它们真的不是很难创建,真正有助于加快开发时间并鼓励代码重用。
更新:
考虑到这个问题的数量,这个问题是得到一个upvote的数量(错误的)答案在下面是获得,这是一个很久以前(一年半!)代码示例与一个图像来展示差异。
代码:
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(); } }
用法:
@using (Html.BeginForm("","",FormMethod.Post)) { var items = new List<SelectListItem>() { new SelectListItem() { Text = "Item 1",Value = "#" },new SelectListItem() { Text = "Item 2",}; <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","Dropdown") </div> </div> }