避免ComboBox发送不在列表中的值

7

我在项目中使用kendo complete for MVC。

我有一些表单中的国家列表,我显示国家名称,但存储国家代码。

我遇到了以下问题:当用户输入不在列表中的内容时,该值将被发送到服务器。如何避免这种情况并发送空值(表示未选择任何值)?

以下是我的代码:

@Html.Kendo()
    .ComboBoxFor(model => model.CountryCode)
    .BindTo(ViewBag.Countries as IEnumerable<SelectListItem>)
    .Filter(FilterType.StartsWith)
    .Placeholder("Country")
    .HtmlAttributes(new { @class = "span9" })

1
这肯定是kendo-ui-combobox中的一个bug - 很好地捕捉到了。 - Paritosh
8个回答

16

这个问题已经在这里解决了。使用ComboBox的change事件,像这样:

change : function (e) {
        if (this.value() && this.selectedIndex == -1) {   //or use this.dataItem to see if it has an object                 
            alert('Invalid Entry!');
            cb.select(1);
        }
    }

这是jsfiddle

编辑:如何在Razor语法中使用

@(Html.Kendo().ComboBox()
    .Name("cb")
    .Events(it => it.Change("cbIsChanged"))
    ...
        )

<script>
    cbIsChanged = function (e) {
        ...
    }
</script>

这个问题可能有点傻,但是这段代码如果用Razor语法来写会是什么样子呢?我尝试转换了一下,但它似乎从未调用该函数。 - Refracted Paladin
1
当非匹配值未更改时,这对于此情况是无用的。不会触发任何更改事件。 - Motlicek Petr

1
Kendo combobox API会返回在下拉框中输入的值 - 如果该项不在列表中。我们需要手动查找该项是否存在于列表中。 链接-ComboBox / API
var comboId = '#movies';
alert(GetComboBoxValue(comboId));

使用此函数获取ComboBox的值。
function GetComboBoxValue(comboId){
    var comboValue = -1;
    $(comboId).data('kendoComboBox').select(function (dataItem) {
        // Note: you have to perhaps change the property - text as per the value
        // this is for the example provided in the link only
        if (dataItem.text == $(comboId').data('kendoComboBox').text()){
            comboValue = dataItem.value;
            break;
        }
    });
    //will return -1, if data is not found from the list
    return comboValue;
}

1

圣骑士,当您使用ASP.NET MVC包装器和组合框时,这里有一个解决方案。以下是razor和javascript代码,以使您的解决方案正常工作。

<div class="form-group">
    @Html.LabelFor(model => model.GlAccount, new { @class = "control-label col-md-4" })
    <div class="col-md-6">
        @(Html.Kendo<OrderRequest>().ComboBoxFor(m => m.GlAccount).DataValueField("Number").DataTextField("Description").Filter(FilterType.Contains).HighlightFirst(true)
                    .DataSource(src => src.Read(read => read.Action("GetGlAccounts", "Lookup", new { area = "" }))).Events(events => events.Change("app.common.onChangeRestrictValues")))
        @Html.ValidationMessageFor(model => model.GlAccount)
</div>

如果输入的值不在定义的值列表中,以下脚本将清空组合框。
<script>
function onChangeRestrictValues(e) {
  if (this.value() && this.selectedIndex == -1) {
    var dt = this.dataSource._data[0];
    this.text(dt[this.options.dataTextField]);
    this.select();
  }
}
</script>

您可以在我的博客上查看更详细的答案和引用链接 http://prestoasp.net/how-to-limit-a-kendo-ui-combobox-drop-down-to-valid-items-using-asp-net-mvc-wrappers/

该文章还提供了我用于原型设计stackoverflow解决方案的github .NET解决方案的链接

干杯


1
我从Telerik论坛获取了这个基础代码,并进行了一些修改,使其更加智能。它将使用当前文本来尝试查找模糊搜索,如果找不到,则会将其清空。
在此处尝试:http://jsfiddle.net/gVWBf/27/
$(document).ready(function() {
    var items = [
        {value : '1',
         desc : 'fred'},
        {value : '2',
         desc : 'wilma'},
        {value : '3',
         desc : 'pebbles'},
        {value : '4',
         desc : 'dino'}
    ];

    var cb = $('#comboBox').kendoComboBox({
        dataSource : items,
        dataTextField : 'desc',
        dataValueField : 'value',
        filter : 'contains',
        change : function (e) {
            if (this.value() && this.selectedIndex == -1) {    
                this._filterSource({
                    value: this.value(),
                    field: this.options.dataTextField,
                    operator: "contains"
                });
                this.select(0);
                if ( this.selectedIndex == -1 ) {                    

                    this.text("");
                }
            }
        }
    }).data('kendoComboBox');


});

1
使用下拉列表控件替代组合框。下拉列表控件的功能与组合框类似,但可以防止用户输入自己的文本内容。

0

这是我使用MVVM的方式:

HTML:

<div id="main_pane_add_truck" data-role="view" data-model="APP.models.main_pane_add_truck">
    <input id="main_pane_add_truck_customer_id" data-role="combobox" data-placeholder="Type a Customer" data-value-primitive="true" data-text-field="Name" data-value-field="CustomerID" 
    data-bind="value: customer_id, source: customer_id_ds, events: { change: customer_id_change }" />
</div>

Javascript模型:

window.APP = {
models: {
    main_pane_add_truck: kendo.observable({
        customer_id: null,
        customer_id_ds: new kendo.data.DataSource({
            type: "odata",
            transport: {
                read: ROOTURL + BODYURL + "MyCustomers"
            },
            schema: {
                model: {
                    fields: {
                        CustomerID: { type: "number" },
                        Name: { type: "string" },
                    }
                }
            }
        }),
        customer_id_change: function customer_id_change(e) {
            try {
                var found = false;
                var combobox = $("#main_pane_add_truck_customer_id").data("kendoComboBox");
                var customer_id = e.data.customer_id;
                var dataSource = this.get("customer_id_ds");
                var data = dataSource.data();
                var data_length = data.length;
                if (data_length) {
                    for (var i = 0; i < data_length; i++) {
                        if (data[i].CustomerID === customer_id) {
                            found = true;
                        }
                    }
                    if (!found) {
                        this.set("customer_id", data[0].CustomerID);
                        combobox.select(0);
                    }
                }
                else {
                    this.set("customer_id", null);
                }
            }
            catch (e) {
                console.log(arguments.callee.name + " >> ERROR >> " + e.toString());
            }
        },
    }),
}
};

0
在Kendo组合框搜索中输入垃圾值后,要设置一个值,请实现以下代码。
$(document).ready(function() {
var items = [
    {value : '1',
     desc : 'fred'},
    {value : '2',
     desc : 'wilma'},
    {value : '3',
     desc : 'pebbles'},
    {value : '4',
     desc : 'dino'}
];

var cb = $('#comboBox').kendoComboBox({
    dataSource : items,
    dataTextField : 'desc',
    dataValueField : 'value',
    filter : 'contains',
    change : function (e) {
        if (this.value() && this.selectedIndex == -1) {    
            this._filterSource({
                value: "",
                field: this.options.dataTextField,
                operator: "contains"
            });
            this.select(1);
        }
    }
}).data('kendoComboBox');

$('#showValue').click(function () {
    alert(cb.value());
});

});


0
为了检查输入到组合框的特定值是否存在,可以使用以下两个JavaScript方法。
你可以按照以下方式进行测试,假设你的组合框的ID是“ComboBoxId”。
@(Html.Kendo().ComboBoxFor(m => m.ComboBoxId)
      .BindTo(Model.ComboBoxItems)
      .Filter(FilterType.Contains)
      .HighlightFirst(true)
)

if (getValueOfKendoCombo('#ComboBoxId') === null) {
   alert('Please select a valid value from the list');
   return;
}

function getValueOfKendoCombo(comboBoxId) {
  var comboBox = $(comboBoxId).data('kendoComboBox');
  var ds = comboBox.dataSource; // data source in order to get a list of data items
  var data = ds['_data']; // object containing data
  var value = comboBox.value(); // value to test
  var itemValue = getByValue(data, value); // loop through all data items and determine if value exists
  if (itemValue == null) { // check if the input value exists
    comboBox.value(null); // set the comboBox text value to null, because it does not exist on the list
    return null; //return value null - use null to check if the value exists
  }
  return itemValue;
}

function getByValue(data, value) {
  // loop through all data items and determine if value exists against the Value of the object, otherwise return null
  for (var i = 0; i < data.length; i++) {
    if (data[i]['Value'] === value) {
      return data[i]['Value'];
    }
  }
  return null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接