You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.Net MVC Kendo Grid复选框选中值为空及StationId绑定控制器问题

问题解答

1. 为什么grid.selectedKeyNames()始终为空?

Kendo Grid的selectedKeyNames()方法需要依赖DataSource中配置的主键字段才能正常返回选中行的键值。你当前的代码里,虽然绑定了StationId列并隐藏,但没有在DataSource的Model中指定它作为主键;同时你开启了PersistSelection(true),这个功能也需要主键来持久化选中状态,双重原因导致无法识别选中行的键值,最终返回空数组。

2. 如何将选中行的StationId绑定到ViewModel并提交到Post操作?

步骤1:配置Grid的DataSource主键

修改Grid的DataSource配置,添加Model并指定StationId为主键,这样selectedKeyNames()就能正常获取选中ID:

@model Project.Lib.ViewModels.Campaigns.CampaignViewModel

@(Html.Kendo().Grid(Model.Stations)
    .Name("grid")
    .DataSource(dataSource => dataSource
        .Custom()
        .PageSize(10)
        .Model(model => model.Id(x => x.StationId)) // 指定主键字段
    )
    .PersistSelection(true)
    .Sortable()
    .Events(ev => ev.Change("onChange"))
    .Columns(columns =>
    {
        columns.Select().Width(50);
        columns.Bound(x => x.StationId).Hidden();
        // 其他列配置...
    })
)

步骤2:在ViewModel中添加存储选中ID的属性

在CampaignViewModel里新增集合属性,用来接收选中的StationId:

public class CampaignViewModel
{
    // 原有属性...
    public List<int> SelectedStationIds { get; set; } = new List<int>();
    public List<StationViewModel> Stations { get; set; }
}

步骤3:收集选中ID并绑定提交

方法1:通过表单隐藏字段绑定到ViewModel

在表单中添加隐藏字段,用于存储选中的ID,提交时自动绑定到ViewModel:

@using (Html.BeginForm("YourPostAction", "YourController", FormMethod.Post))
{
    <!-- 其他表单元素 -->
    @Html.HiddenFor(m => m.SelectedStationIds, new { id = "selectedStationIds" })

    @(Html.Kendo().Grid(Model.Stations)
        // Grid配置(同步骤1)
    )

    <button type="submit">提交</button>
}

修改onChange事件,实时更新隐藏字段的值:

function onChange(arg) {
    var grid = $("#grid").data("kendoGrid");
    var selectedIds = grid.selectedKeyNames();
    // 将数组转为逗号分隔字符串,适配Model绑定
    $("#selectedStationIds").val(selectedIds.join(","));
}

方法2:AJAX直接提交选中ID

如果用AJAX提交,可直接将选中ID数组传给控制器:

function submitSelected() {
    var grid = $("#grid").data("kendoGrid");
    var selectedIds = grid.selectedKeyNames();
    $.ajax({
        url: "/YourController/YourPostAction",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({ selectedStationIds: selectedIds }),
        success: function(res) {
            // 处理成功回调
        }
    });
}

对应的控制器Action:

[HttpPost]
public ActionResult YourPostAction(CampaignViewModel model)
{
    // model.SelectedStationIds 即为选中的StationId集合
    return View();
}

内容的提问来源于stack exchange,提问作者Jesus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:50:33