本文介绍了jQuery multiselect-从数据库分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个jQuery多选插件[ https://github.com/davidstutz/bootstrap- multiselect] 并将其与数据库值动态绑定.

I am using a jquery multiselect plugin [https://github.com/davidstutz/bootstrap-multiselect] and binding it dynamically with database values.

HTML

@Html.ListBoxFor(m => m.Classes, new SelectList(Model.Classes, "Value", "Text"), new { @id = "classList" })

脚本

$('#classList').multiselect({ enableClickableOptGroups: true });

视图中的模型是视图模型,其中包含SelectList

The model in the view is a view model and contains a property for a SelectList

public class SearchControlViewModel 
{
    ....
    public SelectList Classes { get; set; }
}

和控制器中的代码

SearchControlViewModel  model = new SearchControlViewModel()
{
    ....
    Classes = new SelectList(repClass.GetClassesByYear(23), "classID", "classname")
};
return View(model);

除了一件事情外,它的工作原理就像一种魅力-我想像<optgroup>一样添加分组/组头.我该怎么办?

It works like a charm except for one thing - I want to add grouping/group header like <optgroup> does. How can I do that?

用于生成SelectListGetClassesByYear()方法返回一个包含属性int classIDstring classnamestring grade的对象,我希望能够按grade对选项进行分组.

The GetClassesByYear() method used for generating the SelectList returns an object containing properties int classID, string classname and string grade and I want to be able to group the options by grade.

推荐答案

MVC-4不支持选项组,您需要升级到MVC-5才能使用现成的功能.如果要升级,请参考使用OptGroup组构建选择列表同时使用SelectList构造函数和生成IEnumerable<SelectListItem>

Option groups are not supported in MVC-4, and you would need to upgrade to MVC-5 to make use out-of-the-box functions. If you do upgrade, refer Constructing a Select List with OptGroup groups for examples using both the SelectList constructor, and by generating an IEnumerable<SelectListItem>

如果不进行升级,则可以将表示您的组及其选项的模型传递给view,并使用一些javascript/jquery生成元素.首先创建一些其他视图模型

Without upgrading, you could pass a model representing your groups and their options to the view , and use some javascript/jquery to generate the elements. Start by creating some additional view models

public class OptionGroupVM
{
    public string GroupName { get; set; }
    public IEnumerable<OptionVM> Options { get; set; }
}
public class OptionVM
{
    public string Value { get; set; }
    public string Text { get; set; }
    public bool IsSelected { get; set; } // Only applicable if your not binding to a model property
}

然后修改您的主视图模型以包括以下内容

Then modify your main view model to include the following

public class SearchControlViewModel 
{
    ....
    public IEnumerable<int> SelectedClasses { get; set; }
    public IEnumerable<OptionGroupVM> ClassOptions { get; set; }
}

请注意,您当前的模型和ListBoxFor()的使用是不正确的,因为

Note that your current model and use of ListBoxFor() is incorrect because

  1. 您不能将<select multiple>绑定到您的Classes属性为的复杂对象的集合-模型需要为值类型的集合,并且

  1. you cannot bind a <select multiple> to a collection of complex objects which your Classes property is - the model needs to be a collection of value types, and

您不能对绑定的属性和SelectList使用相同的名称-请参考以获得更多详细信息

you cannot use the same name for the property your binding to and the SelectList - refer Will there be any conflict if i specify the viewBag name to be equal to the model property name inside @Html.DropDownListFor for more detail

在控制器中

var data = repClass.GetClassesByYear(23);
var groupedOptions = data.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
{
    GroupName = x.Key.ToString(),
    Options = x.Select(y => new OptionVM()
    {
        Value = y.classId.ToString(),
        Text = y.classcame,
    })
});
SearchControlViewModel model = new SearchControlViewModel()
{
    ....
    SelectedClasses = ...., // the values of the options that will be pre-selected
    ClassOptions = groupedOptions
};
return View(model);

在视图中使用

@Html.ListBoxFor(m => SelectedClasses, Enumerable.Empty<SelectListItem>(), new { id = "classList" })

,它将在没有任何选项的情况下最初生成<select>.然后使用以下脚本生成选项

which will initially generate the <select> without any options. Then use the following script to generate the options

<script type="text/javascript">
    // Get data
    var listBox = $('#classList');
    var selected = @Html.Raw(Json.Encode(Model.SelectedClasses));
    var groups = @Html.Raw(Json.Encode(Model.ClassOptions));

    // Generate options
    createGroupedOptions(listBox, selected, groups);
    // Attach plug-in
    listBox.multiselect({ enableClickableOptGroups: true });

    // This function could be in an external js file
    function createGroupedOptions(element, selected, groups) {
        for (var i = 0; i < groups.length; i++) {
            var group = groups[i];
            var groupElement = $('<optgroup></optgroup>').attr('label', group.GroupName);
            for(var j = 0; j < group.Options.length; j++) {
                var option = group.Options[j];
                var optionElement = $('<option></option>').val(option.Value).text(option.Text);
                if (selected) {
                    if (selected.toString().indexOf(option.Value) >= 0) {
                        optionElement.attr('selected', 'selected')
                    }
                } else {
                    if (option.IsSelected) {
                        optionElement.attr('selected', 'selected')
                    }
                }

                $(groupElement).append(optionElement);
            }
            $(element).append(groupElement);
        }
    }
</script>

这篇关于jQuery multiselect-从数据库分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:16