Telerik MVC Grid:含小数的CustomerId无法触发Ajax Read Action
问题诊断与解决方案
我一眼就揪出了导致小数格式CustomerId无法触发Read操作的两个核心问题:
1. 非法的组件DOM ID
当CustomerId是小数时,你生成的子Grid名称是voucher_123456.123——HTML元素的ID不能包含点号(虽然HTML5理论允许,但Kendo UI组件初始化时会因为这个点号识别失败,直接导致子Grid无法正常创建,自然不会触发Read请求)。
2. 参数传递的URL编码问题
小数作为参数传递时,如果不做处理,可能会在URL解析或MVC参数绑定环节出问题,导致后端无法正确接收参数,请求被静默拦截。
修复步骤
第一步:替换组件名称里的点号
把模板里的组件名称中的.替换成_,用toString().replace('.', '_')处理CustomerId:
- TabStrip名称:
Name("tabStrip_#=CustomerId.toString().replace('.', '_')#") - Voucher Grid名称:
Name("voucher_#=CustomerId.toString().replace('.', '_')#") - Email Grid名称:
Name("email_#=CustomerId.toString().replace('.', '_')#")
第二步:对参数做URL编码
在Read操作中,用encodeURIComponent对CustomerId编码,避免小数的点号在URL中出现解析问题:
.Read(read => read.Action("UserVouchers_Read", "Admin", new { customerId = "#=encodeURIComponent(CustomerId)#" }))
同时确保后端Action的参数类型匹配,比如CustomerId是小数的话,参数定义应为decimal customerId:
public ActionResult UserVouchers_Read(decimal customerId, [DataSourceRequest] DataSourceRequest request) { // 你的业务逻辑代码 }
修改后的关键代码片段
<script id="template" type="text/kendo-tmpl"> @(Html.Kendo().TabStrip() .Name("tabStrip_#=CustomerId.toString().replace('.', '_')#") // 替换点号 .SelectedIndex(0) .Animation(animation => animation.Open(open => open.Fade(FadeDirection.In))) .Items(items => { items.Add().Text("Voucher Information").Content(@<text> @(Html.Kendo().Grid<BSD.VoucherRedemption.Model.UserVoucherVM>() .Name("voucher_#=CustomerId.toString().replace('.', '_')#") // 替换点号 .Columns(columns => { columns.Bound(v => v.UserVoucherId).Width(90).Title("Voucher ID").Filterable(false); columns.Bound(v => v.VoucherNo); columns.Bound(v => v.VoucherValue).Visible(false); columns.Bound(v => v.IsVoucherRedeemedStr).Title("Is Voucher Redeemed"); columns.Bound(v => v.CreatedDate).Title("Assigned Date"); }) .DataSource(dataSource => dataSource .Ajax() .PageSize(5) .ServerOperation(false) .Read(read => read.Action("UserVouchers_Read", "Admin", new { customerId = "#=encodeURIComponent(CustomerId)#" })) // URL编码 ) .Pageable() .Sortable() .ToClientTemplate()) </text>); items.Add().Text("Email Activity").Content(@<text> @(Html.Kendo().Grid<BSD.VoucherRedemption.Model.UserVoucherVM>() .Name("email_#=CustomerId.toString().replace('.', '_')#") // 替换点号 .Columns(columns => { columns.Bound(v => v.UserVoucherId).Width(50).Title("Email ID").Filterable(false); columns.Bound(v => v.CreatedDate).Width(50).Title("Email Sent Date"); }) .DataSource(dataSource => dataSource .Ajax() .PageSize(5) .ServerOperation(false) .Read(read => read.Action("UserEmails_Read", "Admin", new { customerId = "#=encodeURIComponent(CustomerId)#" })) // URL编码 ) .Pageable() .Sortable() .ToClientTemplate()) </text>); }) .ToClientTemplate()) </script>
额外检查点
- 确认后端Action的参数类型和前端传递的类型完全匹配(比如前端是小数,后端用
decimal而非string或int) - 打开浏览器开发者工具(F12),查看Network标签页,展开子Grid时观察是否有请求发送,以及请求的URL、参数和后端返回状态码是否正常
内容的提问来源于stack exchange,提问作者Kamran.Zafar
相关产品推荐
相关产品推荐

