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

时间:2013-09-18 11:14:50

标签: combobox kendo-ui

我正在项目中使用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" })

8 个答案:

答案 0 :(得分:13)

涵盖同一问题here。使用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

编辑: How to use in Razor syntax

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

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

答案 1 :(得分:1)

Kendo组合框API返回在组合框中输入的值 - 如果列表中没有项目。我们必须手动查找该项是否存在于列表中。

<强> Link - 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;
}

答案 2 :(得分: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');


});

答案 3 :(得分:1)

Paladin,这是使用ASP.NET MVC包装器时的解决方案。一个组合框。以下是剃须刀&amp; 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>

您可以使用@ my blog使用的参考资料查看更全面的答案 http://prestoasp.net/how-to-limit-a-kendo-ui-combobox-drop-down-to-valid-items-using-asp-net-mvc-wrappers/

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

干杯

答案 4 :(得分:1)

使用DropDownList小部件而不是ComboBox。 DropDownList非常相似,但阻止用户输入他们自己的文本。

答案 5 :(得分: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());
});

});

答案 6 :(得分: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());
            }
        },
    }),
}
};

答案 7 :(得分: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;
}