在页面加载处尝试填充Telerik DDL时,会出现错误



如何在页面上填充Telerik下拉列表?

当我尝试填充下拉列表时,我会收到以下错误(在下面的强调行):

Error: 'data(...)' is null or not an object

这是我尝试填充Telerik DDL的方式:

$(function(){
var values = [];
for (var i = 1; i < 10; i++) { 
values.push({ Text: i, Value: i });
}
****$("#MyDdl").data("tDropDownList").dataBind(values);****
});

也是这样尝试的:

 $(function(){
    onDataBinding();
    });
function onDataBinding(e) {
        var MyDdl = $('#MyDdl').data('tDropDownList');
        var values = [];
        for (var i = 1; i < 10; i++) {  
    values.push({ Text: i, Value: i });
    }
      ****MyDdl.dataBind(values);****
    };

,但在上面强调的线上遵循未定义的错误:

Error: 'undefined' is null or not an object

注意:添加一个按钮并加载DDL在按钮点击事件上确实填充了Telerik下拉列表。这样做的方式很好:

    $(function(){
   var values = [];
        for (var i = 1; i < 10; i++) {             
        values.push({ Text: i, Value: i });
        }
        $("#MyDdl").data("tDropDownList").dataBind(values);            
    });

任何帮助都非常感谢。

您需要在下拉列表的Onload事件处理程序中填充它:

.ClientEvents(events => events.OnLoad("ddl_onLoad").OnChange("ddl_onChange")

处理者:

function ddl_onLoad(e) {
    var ddl = $(this).data('tDropDownList');
    ddl.dataBind([
        { Text: 'Product 1', Value: '1' },
        { Text: 'Product 2', Value: '2', Selected: true },
        { Text: 'Product 3', Value: '3' },
        { Text: 'Product 4', Value: '4' }
    ]);
}
function ddl_onChange(e) {
    //var ddl = $(this).data('tDropDownList');
    console.log(e.value);
}

不要直接调用ondatabinding()函数。

查看

   <%= Html.Telerik().DropDownList()
                          .Name("DropDownList")
                          .ClientEvents(events => events
                          .OnDataBinding("onDropDownListDataBinding"))
        %>

JS

   <script type="text/javascript">
            function onDropDownListDataBinding(e) {
                    var MyDdl = $('#MyDdl').data('tDropDownList');
                     MyDdl .dataBind([
            { Text: "Product 1", Value: "1" },
            { Text: "Product 2", Value: "2", Selected: true },
            { Text: "Product 3", Value: "3" },
            { Text: "Product 4", Value: "4" },
            { Text: "Product 5", Value: "5" }            
        ]);
            };
    </script>

最新更新