这个看起来很简单,只是不确定在哪里处理它。我正在通过REST JSON从SQL数据库中检索列名值。下拉列表中的值具有预期的下划线(Customer_Name)。我想显示一个没有下划线的“友好”(客户名称)版本,但仍然将我的值(Customer_Name)发送到我的REST服务。我看了看Underscore.js,但不知道从哪里开始,这可能比我想象的要简单。谢谢!
答案 0 :(得分:1)
我不知道您是如何从休息服务中接收数据的。
但基本上,您只需映射REST服务收到的数据,根据需要更改值。
以下是一些示例代码:
// Call to the REST service and when done call the callback function loadDDL
$.ajax({
type: "POST",
url: "my-rest-service"
}).done(loadDDL);
// Callback function when returning from the REST service
// -> load data in the DDL (here, it has the id "my-ddl")
function loadDDL(data) {
$("#my-ddl").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: _.map(data, makeFriendlyName),
index: 0
});
}
// Function used by the _.map function in order
// change dynamically the labels in the DDL
function makeFriendlyName(obj) {
return {
text: obj.text,
value: obj.value.replace("_", " ")
};
}
编辑:
基于OP的小提琴,下面是使用模板而不是直接更改数据源的示例代码:
function loadDDL(data) {
$("#my-ddl").kendoDropDownList({
autoBind: true,
dataTextField: "DOMAINQUERY",
dataValueField: "COLUMN_NAME",
dataSource: dataSourceSearch1,
template: "${DOMAINQUERY.replace(/_/g, ' ')}"
});
}
编辑2:
为了直接转换数据源,我再次通过动态更改数据源的change
事件中的文本来重新映射数据源:
var dataSourceSearch1 = new kendo.data.DataSource({
transport: {
read: {
url: "http://demos.kendoui.com/service/Customers",
dataType: "jsonp"
}
},
change: changeDS // <-- Here add a change event : each time the datasource changes, this event is being raised
});
// This is the function call when the DS changes
// the data stuff is in the `items` property which is the object send via the REST service
function changeDS(datasource) {
_.map(datasource.items, makeFriendlyName);
}
// Function to apply to each data -> here I just replace all spaces in the
// `ContactName` field by `_`
function makeFriendlyName(data) {
data.ContactName = data.ContactName.replace(/ /g, '_');
return data;
}
// Fill the DDL with the previous datasource
var cboSearchField1 = $("#cboSearchField1").kendoDropDownList({
dataTextField: "ContactName",
dataValueField: "ContactName",
filter: "contains",
autobind: true,
select: cboSearchField1_Selected,
change: cboSearchField1_onChange,
dataSource: dataSourceSearch1
}).data("kendoDropDownList");