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

Kendo MVC Grid整数数值列输入小数变0的解决方法咨询

Kendo MVC Grid 整数列处理小数输入的解决方案

针对绑定到int类型Quantity属性的Grid列,输入小数后变为0的问题,提供两种符合预期的实现方案:

方案1:禁止输入小数(仅允许整数)

通过配置Kendo NumericTextBox的限制规则,直接阻止用户输入小数:

方式A:直接在列中配置编辑器

columns.Bound(c => c.Quantity)
       .Title("Quantity")
       .Width(100)
       .Editor(editor => editor.NumericTextBox()
           .Format("{0:n0}") // 显示无小数格式
           .Step(1) // 上下箭头仅增减整数
           .RestrictDecimals(true)); // 禁止输入小数点

方式B:使用编辑器模板(复用性更高)

  1. 在Views/Shared/EditorTemplates目录下创建IntegerNumericTextBox.cshtml:
@model int?

@(Html.Kendo().NumericTextBoxFor(m => m)
    .Format("{0:n0}")
    .Step(1)
    .HtmlAttributes(new { style = "width: 100%;" })
    .RestrictDecimals(true)
)
  1. 在Grid列中引用该模板:
columns.Bound(c => c.Quantity)
       .Title("Quantity")
       .Width(100)
       .EditorTemplateName("IntegerNumericTextBox");

方案2:输入小数后自动四舍五入至最近整数

通过编辑器的事件处理,将输入的小数值自动转换为最近整数:

步骤1:配置列编辑器及事件

columns.Bound(c => c.Quantity)
       .Title("Quantity")
       .Width(100)
       .Editor(editor => editor.NumericTextBox()
           .Format("{0:n0}")
           .Step(1)
           .Events(e => e.Change("onQuantityChange"))); // 绑定值变更事件

步骤2:添加JavaScript处理函数

function onQuantityChange(e) {
    const value = e.sender.value();
    if (value !== null) {
        const roundedValue = Math.round(value);
        e.sender.value(roundedValue);
    }
}

也可以使用Parse事件在输入解析阶段完成四舍五入:

columns.Bound(c => c.Quantity)
       .Title("Quantity")
       .Width(100)
       .Editor(editor => editor.NumericTextBox()
           .Format("{0:n0}")
           .Step(1)
           .Events(e => e.Parse("onQuantityParse")));
function onQuantityParse(e) {
    e.value = Math.round(e.value);
}

内容的提问来源于stack exchange,提问作者Manoj T V

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:05:44