add search functionality on DropDownListFor

2019-02-15 14:46发布

问题:

I am wondering if any one could help me with a issue I am facing. I am trying to create a search on a DropDownListFor using razor.

private List<SelectListItem> LoadStockitems()
{
    List<SelectListItem> selectItems = new List<SelectListItem>();
    foreach (var role in GetStockItemsFromDB())
    {
        SelectListItem listItem = new SelectListItem();
        listItem.Value = role.StockCode;
        listItem.Text = role.Description;
        selectItems.Add(listItem);
    }
    return selectItems;
}

ViewBag.AllStockList  = LoadStockitems();

View

@Html.DropDownListFor(x =>
    x.StockCode,
    (IEnumerable<SelectListItem>)ViewBag.AllStockList,
    new {
        @class = "form-control",
        @Value = @Model.Description,
        onchange = "this.form.submit();"
})

I can do this using Html but I can not figure out how to do using razor. In HTML,

@using (Html.BeginForm("Hello", "Hello"))
{
    <div class="form-group">
        <label class="control-label"> Select A Customer </label>
        <select class="selectpicker bs-select form-control"
                name="CustomerID"
                onchange="this.form.submit()"
                data-show-subtext="true"
                data-live-search="true">
            @foreach (var Customer in @Model.CustomerSelect)
            {
                <option value="@Customer.CustomerID"
                        data-subtext="@Customer.ContactName">
                    @Customer.Name
                </option>
            }
        <select>
        <input type="hidden" name="SearchButton" value="true">
    </div>
}

How can you create a search on a DropDownListFor and is there anything like subtext attribute...?

回答1:

You are using a bootstrap plugin called bootstrap-select. To use it in razor view, do this.

@Html.DropDownListFor(x =>
    x.StockCode,
    (IEnumerable<SelectListItem>)ViewBag.AllStockList,
    new
    {
        @class = "form-control selectpicker",
        @Value = @Model.Description,
        onchange = "this.form.submit();"
})

Don't change anything in the razor view except adding the class selectpicker. Now initialize the plugin by setting the options in JavaScript like this.

$(document).ready(function() {
    $('.selectpicker').selectpicker({
        liveSearch: true,
        showSubtext: true
    });
});

Demo: http://jsfiddle.net/codeandcloud/a5r2vyu2/1/
Documentation: https://silviomoreto.github.io/bootstrap-select/options/

To add data-* attributes in razor syntax replace - with _ like this.

@Html.DropDownListFor(x =>
    x.StockCode,
    (IEnumerable<SelectListItem>)ViewBag.AllStockList,
    new
    {
        @class = "form-control selectpicker",
        @Value = @Model.Description,
        onchange = "this.form.submit();",
        data_show_subtext="true",
        data_live_search="true"
})

Read this and this.