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

Kendo NumericTextBox事件中获取值为旧值问题求助

解决Kendo NumericTextBox值获取滞后/为null的问题

问题场景

我在排查Kendo NumericTextBox的异常时遇到了两个核心问题:

  • 当把myTextBox的值设为5并触发change事件时,调用myTextBox.value()获取到的值是null;
  • 把值改为10再次触发事件时,获取到的却是旧值5。

对比表单中正常工作的文本框后发现:二者配置看似一致,但异常文本框的Kendo包装器对象的value属性值滞后,不过查看DOM元素的element属性时,值是正确且实时的。

相关代码如下:

模型属性

[UIHint("Decimal")]
[Display(Name = "Example")]
public decimal? MyTxt{ get; set; }

Decimal模板(Decimal.cshtml)

@model decimal?
@{
    var defaultHtmlAttributesObject = new { style = "width:100%" };
    var htmlAttributesObject = ViewData["htmlAttributes"] ?? new { };
    var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesObject, defaultHtmlAttributesObject);
}
@(Html.Kendo().NumericTextBoxFor(m => m)
    .Format("#.00")
    .HtmlAttributes(htmlAttributes)
)

UI声明

@Html.EditorFor(m => m.MyTxt, new { htmlAttributes = new { @style="width: 100%", @readonly = "readonly" } })

初始JavaScript代码

var myTextBox = $('#MyTxt').data('kendoNumericTextBox');
$(document).on('change', '#foo', function(){
    var test = myTextBox.value();
})

问题根源

之前我是在document ready里用jQuery原生的change事件绑定逻辑:

$('#MyTxt').change({ source: $('#MyTxt'), destination: someObject, isTwoMan: true, crewType: LaborType.Set }, SomeCalcFunction);

这里的关键问题是:jQuery原生的change事件触发时机早于Kendo NumericTextBox自身的事件。当jQuery的change事件触发时,Kendo还没完成对控件值的同步更新,所以包装器的value()方法拿到的要么是未初始化的null,要么是上一次的旧值。

解决方案

改用Kendo官方推荐的事件绑定方式,确保在Kendo完成值更新后再执行你的逻辑:

方式1:在初始化控件时绑定事件

如果是自己初始化NumericTextBox,可以直接在配置里加Change事件:

$("#MyTxt").kendoNumericTextBox({
    format: "#.00",
    change: function(e) {
        // 这里可以安全获取最新值
        var newValue = this.value();
        // 执行你的SomeCalcFunction逻辑
        SomeCalcFunction({ 
            data: { 
                source: this.element, 
                destination: someObject, 
                isTwoMan: true, 
                crewType: LaborType.Set 
            } 
        });
    }
});

方式2:通过Kendo的bind方法绑定事件

如果控件是通过MVC Helper生成的(就像你的场景),可以用Kendo的bind方法来绑定事件:

$(document).ready(function() {
    var myTextBox = $('#MyTxt').data('kendoNumericTextBox');
    // 绑定Kendo的change事件
    myTextBox.bind("change", function(e) {
        var newValue = this.value();
        // 传递需要的参数执行计算逻辑
        SomeCalcFunction({ 
            data: { 
                source: this.element, 
                destination: someObject, 
                isTwoMan: true, 
                crewType: LaborType.Set 
            } 
        });
    });
});

这样就能保证每次触发事件时,获取到的都是NumericTextBox的最新值,不会再出现滞后或null的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:28:53