2015年10月8日 星期四

【ASP.NET MVC】JQuery MultiSelect ListBox use Harvest chosen plugin


在 ASP.NET MVC WebApp proj 中引用 Harvest chosen plugin

載下來之後會用到的是
然後在 layout
<link rel="stylesheet" href="~/Content/prism.css" />
<link rel="stylesheet" href="~/Content/chosen.min.css" />
<script src="~/Scripts/chosen.jquery.min.js"></script>
<script src="~/Scripts/prism.js"></script>

最後要補 script 設定,我是設在個別頁
@section scripts {
    <script>
        var config = {
            '.chosen-select': {},
            '.chosen-select-deselect': { allow_single_deselect: true },
            '.chosen-select-no-single': { disable_search_threshold: 10 },
            '.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
            '.chosen-select-width': { width: "95%" }
        }
        for (var selector in config) {
            $(selector).chosen(config[selector]);
        }
    </script>
}


Controller 給予
public ActionResult Test()
{
    var model = new MyViewModel();

    // preselect items with values 2 and 4
    model.SelectedValues = new[] { 2, 4 };

    // the list of available values
    model.Values = new[]
    {
        new SelectListItem { Value = "1", Text = "item 1" },
        new SelectListItem { Value = "2", Text = "item 2" },
        new SelectListItem { Value = "3", Text = "item 3" },
        new SelectListItem { Value = "4", Text = "item 4" },
    };

    return View(model);
}

cshtml 使用
@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectedValues, Model.Values, new { @class = "chosen-select", multiple = "multiple", style = "width: 300px", data_placeholder = "請選擇" })
    <br />
    <input type="submit" value="InputLst" />
}

data_placeholder 是未選取時顯示的提示

ref: Harvest Chosen

7/1/17
更新範例 (跟內文會有少許出入)

沒有留言:

張貼留言