如何将Bootstrap下拉样式应用于ASP.NET MVC DropDownList?

时间:2014-10-24 20:10:11

标签: asp.net-mvc twitter-bootstrap

给出以下MVC剃刀代码,它从列表中创建一个下拉列表:

@Html.DropDownList("MyTestList", null, new { @class = "btn btn-default dropdown-toggle" })

这将创建以下下拉列表:

dropdown

使用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>

它会显示如下的下拉列表:

image

问题: 使用@Html.DropDownList时使用MVC中的HTML代码是否可以获得相同的外观?

8 个答案:

答案 0 :(得分:49)

这是非常可能的,而且非常简单。请阅读: DropDownList bootstrap styling

您只需要:

@Html.DropDownList("movieGenre", "All", new { @class = "form-control"})

@Html.DropDownListFor(model => model.MovieGenreModel, SelectList, new { @class = "form-control"})

答案 1 :(得分:41)

无法使用Razor的@Html.DropDownList()方法创建您提到的Bootstrap下拉列表。虽然创建自己的HTML帮助程序非常容易,但却会创建创建上述下拉列表所需的代码。

有很多教程和指南(such as this one)将引导您完成创建自定义HTML帮助程序的过程。它们真的不是那么难以创建,并且可以真正帮助加快开发时间并鼓励代码重用。

<强>更新

考虑到这个问题的关注程度正在得到以下(不正确)答案得到的upvotes的数量,这是一个早就应该(一年半!)的代码示例,带有一个图像来证明差异。

您可以将此代码复制并粘贴到您的解决方案中,它应该可以正常运行。

enter image description here

代码:

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", 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>

}

答案 2 :(得分:5)

@using (Html.BeginForm("Index", "ELibrary"))
{
@Html.DropDownListFor(m => m.Status, new SelectList(Model.StatusItems, "key", "value"), "-- Status --", new { onchange = "this.form.submit();", @class = "form-control" })
}

你只需要添加@ class =“form-control”。它工作正常。但我也把它放在一个Html.Begin表格();

答案 3 :(得分:1)

试试这段代码:

  @Html.DropDownListFor(model => model.MovieGenreModel, SelectList,
                   new { @class = "form-control",aria_describedby="dropdownMenu1"})

答案 4 :(得分:1)

我在ASP.net MVC中有一个引导按钮,其中包含我在当前工作场所使用的真实示例。

<div class="dropdown" style="display:inline-block">
            <button class="btn btn-warning dropdown-toggle" type="button" data-toggle="dropdown" value="@Model.Id"  runat="server"><span class="glyphicon glyphicon-user"></span> Assign <span class="caret"></span></button>
            <ul class="dropdown-menu" onclick="location.href='@Url.Action("AssignTicket", "Home", new {AssignId = Model.Id })'">
                @foreach (var user in (IEnumerable<SelectListItem>)ViewBag.User)
                {
                    <li>@user.Text</li>
                }
            </ul>
</div>

View.user直接从数据库获取用户名。 Jope这是你们有些人想要的。

答案 5 :(得分:1)

对于寻找 .Net 核心实现的人,我在这里调整了 Joseph Woodward's answer

public class BootstrapHtml
{
    public static HtmlString 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.Append(" " + label);
        button.InnerHtml.AppendHtml(BuildCaret());

        //button.InnerHtml += " " + BuildCaret();

        var wrapper = new TagBuilder("div");
        wrapper.AddCssClass("dropdown");

        wrapper.InnerHtml.AppendHtml(button);
        wrapper.InnerHtml.AppendHtml(BuildDropdown(id, selectListItems));

        //wrapper.InnerHtml += button;
        //wrapper.InnerHtml += BuildDropdown(id, selectListItems);

        using (var writer = new System.IO.StringWriter())
        {
            wrapper.WriteTo(writer, HtmlEncoder.Default);
            string asd = writer.ToString();
            return new HtmlString(writer.ToString());
        }
    }

    private static TagBuilder BuildCaret()
    {
        var caret = new TagBuilder("span");
        caret.AddCssClass("caret");

        return caret;
    }

    private static TagBuilder 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");

        foreach (var item in items)
        {
            list.InnerHtml.AppendHtml("<li role=\"presentation\">" + BuildListRow(item) + "</li>");
        }
        //items.ForEach(x => list.InnerHtml += "<li role=\"presentation\">" + BuildListRow(x) + "</li>");

        return list;
    }

    private static string BuildListRow(SelectListItem item)
    {
        var anchor = new TagBuilder("a")
        {
            Attributes =
            {
                {"role", "menuitem"},
                {"tabindex", "-1"},
                {"href", item.Value}
            }
        };
        var span = new TagBuilder("span");
        span.InnerHtml.Append(item.Text);
        anchor.InnerHtml.AppendHtml(span);
        //anchor.SetInnerText(item.Text);

        using (var writer = new System.IO.StringWriter())
        {
            anchor.WriteTo(writer, HtmlEncoder.Default);
            string asd = writer.ToString();
            return writer.ToString();
        }
    }
}

答案 6 :(得分:0)

添加@class = "form-control"不适用于@Html.DropDownListFor。也就是说,您可以通过复制这些样式(例如通过开发人员工具)来镜像其他"form-control"输入的样式,然后将@Html.DropDownListFor包装在您提供id的div中(例如#my-selector)。为div的孩子设置样式,例如:#my-selector&gt;选择{... normal bootstrap form-control styles}

答案 7 :(得分:0)

我实施了您的解决方案并且有效。

现在需要的是BootstrapHtml.DropdownFor,而不仅仅是下拉列表。我们确实需要能够在下拉选择更改时更新模型属性。