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

含外键列的Syncfusion Grid更新时控制器参数为null的解决方法

ASP.NET Core 8 MVC Syncfusion Grid外键列导致Update方法参数为null的解决办法

问题原因

添加外键列后,Syncfusion Grid提交更新请求时,会同时发送CountryId和Country字段到后端。但你的ForeignCityModel中Country是string类型,而Grid实际提交的Country是包含Id和Name的对象(来自外键数据源),这会导致ASP.NET Core模型绑定无法正确解析JSON,最终CRUDModel<ForeignCityModel>参数变为null。

解决方案

方案1:忽略模型中不需要绑定的Country属性

更新操作仅需CountryId关联外键,Country仅用于前端显示,无需参与模型绑定。用[JsonIgnore]标记该属性,让绑定过程忽略它:

public class ForeignCityModel
{
    public int Id { get; set; }
    public string City { get; set; }
    [JsonIgnore] // 添加该特性忽略绑定
    public string Country { get; set; }
    public int CountryId { get; set; }
    public bool IsUSOrCanada { get; set; }
    public DateTime Modified { get; set; }
}

方案2:通过前端事件清理提交数据

在Grid的actionBegin事件中拦截更新请求,移除多余的Country字段,只保留必要参数:

在视图的Scripts区块添加事件处理函数:

@section Scripts {
    <script>
        function onActionBegin(args) {
            // 仅在更新操作时清理数据
            if (args.requestType === 'save' && args.action === 'update') {
                delete args.data.Country;
            }
        }

        async function onActionFailure(e) {
            const stream = e.error[0].error.body;
            const reader = stream.getReader();
            const { value } = await reader.read();
            let text = new TextDecoder().decode(value);
            let error = "Action failed.";
            try {
                const json = JSON.parse(text);
                error = json.errorMessage;
            } catch {
                // text is not valid JSON – ignore
            }
            toastr.error(error);
        }

        function onActionComplete(args) {
            if (args.requestType === 'save' || args.requestType === 'delete')
                toastr.success('Saved.');
        }
    </script>
}

然后在Grid组件上绑定该事件:

<ejs-grid id="js-grid" actionBegin="onActionBegin" actionFailure="onActionFailure" actionComplete="onActionComplete" 
          allowResizing="true" allowFiltering="false" allowPaging="true" height="610" rowHeight="30" 
          enableAutoFill="true" allowSelection="true" showColumnChooser="true"
          toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel", "Search", "ColumnChooser" })">
    <!-- 其他配置保持不变 -->
</ejs-grid>

方案3:显式配置外键列的编辑类型

指定外键列的编辑类型为下拉框,确保提交的是CountryId而非完整对象:

<e-grid-column field="@nameof(ForeignCityModel.CountryId)" headerText="Country" 
               foreignKeyValue="Name" foreignKeyField="Id" dataSource="@Model.Countries">
    <e-edit-settings editType="dropdownedit"></e-edit-settings>
</e-grid-column>

验证方式

修改完成后,通过浏览器开发者工具(F12)查看Network标签下的更新请求,确认提交的JSON仅包含Id、City、CountryId、IsUSOrCanada、Modified字段,无多余的Country对象,此时模型绑定即可正常解析,crud参数不会再为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 18:05:09