"Select all" 在 Kendo 多选 (MVC)

"Select all" in Kendo MultiSelect (MVC)

我有一个带有一些自定义编辑器的 Kendo 网格,其中一个是 multiselect。我有一个用于编辑器的 cshtml 文件,如下所示:

@model IEnumerable<ManageSitesInTemplateViewModel>
@(Html.Kendo().MultiSelectFor(m => m)
    .AutoClose(false)
    .DataTextField("SiteName")
    .DataValueField("SiteId")
    .BindTo((IEnumerable<ManageSitesInTemplateViewModel>)ViewData["sites"])
)

它使用 BindTo,这是从请求页面时创建的 ViewData 获取的数据。一切正常,没有问题。

问题是我一直在尝试使用各种实现来实现“select/deselect 全部”按钮,但都无济于事。我怀疑这是因为我使用 BindTo.

以下是我尝试过的一些示例:

Kendo select/deselect all items demo

Kendo forums: Select All items after data is read

我可以正确地获得 select 一切的按钮,但是当一切都被 selected 并且我尝试将条目保存在网格上时,操作没有被触发。没有任何反应,selection 重置。如果我手动 select 仍然有效。

这是怎么回事? 自定义编辑器的完整代码:

@model IEnumerable<ManageSitesInTemplateViewModel>
@(Html.Kendo().MultiSelectFor(m => m)
    .AutoClose(false)
    .DataTextField("SiteName")
    .DataValueField("SiteId")
    .BindTo((IEnumerable<ManageSitesInTemplateViewModel>)ViewData["sites"])
)

<button class="k-button" id="selectall123">Select All</button>

<script type="text/javascript">
    $(document).ready(function () {
        $("#selectall123").on('click', function (e) {
            e.preventDefault();
            var multiselect = $('#Sites').data("kendoMultiSelect");

            var all = $.map(multiselect.dataSource.data(), function (dataItem) {
                return dataItem.SiteId;
            });
            multiselect.value(all);
        });
    });
</script>

在从 Telerik 自己的论坛获得帮助后,他们为我提供了这个有效的解决方案。我只是直接引用他们的话:

When using the MultiSelect's value() method, the model bound to the widget will not be updated, because this method does not trigger a change event. You can bypass this by manually triggering change after selecting the items:

答案代码:

<script type="text/javascript">
    $(document).ready(function () {
        $("#selectall123").on('click', function (e) {
            // ...
             
            multiselect.value(all);
            multiselect.trigger("change");
        });
    });
</script>

我遇到了同样的问题。这是一个对我有用的例子。

@(Html.Kendo().MultiSelect().Name("Config_MetricType")
    .BindTo(Model.Config_MetricTypes)
    .DataValueField("MetricTypeId")
    .DataTextField("MetricDisplayName")
    .Events(e => e.DataBound("selectAllMetrics"))
    .HtmlAttributes(new { style = "width: 50%", @class = "pull-left" }))

JavaScript函数:

function selectAllMetrics() {
    var Config_MetricType = $("#Config_MetricType").data("kendoMultiSelect");
    var all = $.map(Config_MetricType.dataSource.data(), function (dataItem) {
        return dataItem.MetricTypeId; //DataValueField
    });
    Config_MetricType.value(all);
    Config_MetricType.trigger("change");
}