I have setup a Kendo Grid with a column which contains a ComboBox editor template assigned. This works well and retrieves the items I am expecting:
columnSchema.push({ field: "Comment", title: 'Comment', editor: commentDropDownEditor, template: "#=Comment.Description#" });
Produces the following:
My issue is that I am now trying to extend the properties of the 'Comment' column so that users can enter new items i.e. comments that will, in turn, be saved to the database for reuse.
So far, I have done the following...
Setup the commentDropDownEditor function:
function commentDropDownEditor(container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoComboBox({
suggest: true,
change: onComboBoxChange,
autoBind: false,
optionLabel: "Select comment...",
dataTextField: "Description",
dataValueField: "ID",
dataSource: {
type: "json",
autoSync: true,
transport: {
read: "CommentsAsync_Read",
create: {
url: "CommentsAsync_Create",
dataType: "json"
}
}
}
});
$('<span class="k-invalid-msg" data-for="' + options.field + '"></span>').appendTo(container);
}
Hooked up the change event to the following function:
function onComboBoxChange(e) {
var combo = e.sender;
// check if new value is a custom one
if (!combo.dataItem()) {
// select the newly created dataItem after the data service response is received
combo.one("dataBound", function () {
combo.text(combo.text());
});
// create a new dataItem. It will be submitted automatically to the remote service (autoSync is true)
combo.dataSource.add({ Description: combo.text() });
}
}
I can see the onComboBoxChange function being hit through the Console Window (including the line where the new item is being added to the combo box datasource) but the associated Create transport function is not being executed nor is the item being added to the Combo Box.
Create function in the Controller is as follows:
[HttpPost]
public async Task<ActionResult> CommentsAsync_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<Comment> comments)
{
if (comments.Any())
{
//await _manager.CreateCommentAsync(comments);
}
return Json(comments.ToDataSourceResult(request, ModelState));
}
Is there something I am missing/doing wrong here to get this to work?
Related
I'm fairly new to Kendo UI and got the basics for my code here : http://demos.telerik.com/kendo-ui/dropdownlist/cascadingdropdownlist
I got 2 api calls, where the first take no parameters and return a list if items (Id, Name)
The second api call take in an Id, and return a seconds list of items (also just an object with Id and Name)
From this I want to have 2 cascading kendo dropdowns.
However my problem is the second one's url always have the id being null or empty, and I cannot figure out what is the right syntax:
// First dropdown, all good
var controllers = $("#Controller").kendoDropDownList({
optionLabel: "Select controller...",
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
serverFiltering: true,
transport: {
read: "/SharedData/GetControllers/"
}
}
}).data("kendoDropDownList");
// second dropdown, always hit the api method with the id being null or empty (depending on syntax for url)
var actions = $("#Action").kendoDropDownList({
autoBind: true,
cascadeFrom: "controllers",
cascadeFromField: "Id",
optionLabel: "Select Action...",
dataTextField: "Id",
dataValueField: "Name",
dataSource: {
serverFiltering: true,
transport: {
// HELP: need pass id to this route (which is id of selected controller)
read: "/SharedData/GetControllerActions/id=" + $("#Controller").data("kendoDropDownList").text()
}
}
}).data("kendoDropDownList");
I believe the problem is that your datasource only gets set one time - at the time of initialization - and at this time the value of the dropdown is null. What i would do is add a change event on the first dropdown like this:
var controllers = $("#Controller").kendoDropDownList({
optionLabel: "Select controller...",
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
serverFiltering: true,
transport: {
read: "/SharedData/GetControllers/"
}
},
change: function(e) {
setSecondDS();
}
}).data("kendoDropDownList");
var setSecondDS = function() {
//initialize your new kendo datasource here
var dataSource = new kendo.data.DataSource({
//your stuff here
transport:
serverFiltering:
});
$("#Action").data("kendoDropDownList").setDataSource(dataSource);
}
I have a Kendo UI combobox object something like this :
widget: "kendoComboBox",
options: {
dataTextField: "#:userFirstName# #:userLastName#",
dataValueField: "userId",
template: "#:userFirstName# #:userLastName#",
change: function (e) {
that.model.fn.bringUserData();
}
}
I can arrange the template, but i cannot dataTextField value depends on that template. It is possible to make it "userId" etc. But seems not possible to set selected value as #:userFirstName# #:userLastName#. (dataTextFieldTemplate doesn't work.)
Could you help me to solve this?
Correct, you cannot make it a composition of two fields. It needs to be a field per se. What you can do is when reading data from the DataSource create an additional field that is the concatenation of those two fields. You can add to you DataSource definition something like this:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "..."
}
},
schema: {
parse: function(response) {
$.each(response, function(idx, elem) {
elem.fullName = elem.firstName + " " + elem.lastName;
});
return response;
}
}
});
Then the options for the combobox are simply:
options: {
dataTextField: "fullName",
dataValueField: "userId",
...
}
See it in action here : http://jsfiddle.net/OnaBai/12hpLeux/1/
I want to have multiple datatextField column as im returning a custom List which returns me list with property Name,Status and PID, but i can't use multiple columns on my DatatextField i-e Name and Status so that i can use them for my template property shown below,
Name and Status column is necessary for my template and PID is necessary for my datavalueField
it shows me error for Status is undefined
<script>
$(document).ready(function () {
$("#prog").kendoDropDownList({
dataTextField: "Name",
dataValueField: "PID",
optionLabel: "...select programme...",
headerTemplate: '<div class="dropdown-header">' +
'<span class="k-widget k-header">status</span>' +
'<span class="k-widget k-header">Name</span>' +
'</div>',
valueTemplate: '<span class="selected-value">#: Name#</span>',
template: '<span class="k-state-default">#: Status#</span>' +
'<span class="k-state-default"><h3>#: Name#</h3></span>',
dataSource: {
transport: {
read: {
dataType: "json",
url: "#Url.Action("GetProgrammesInfo", "Programme", new { ECID = ViewBag.ECID as int? })"
}
}
},
change: function (e) {
var value = this.value();
alert(value);
}
});
var dropdownlist = $("#prog").data("kendoDropDownList");
});
</script>
I think to reference a property inside the template that isn't the textfield or valuefield, you will need to use data.Status.
If I switch to that, it seems to work. Also if I switch the dataTextField to Status, I get the error on the Name, and if I change the Name to data.Name, it works again.
Somewhat working sample... http://jsbin.com/xemef/1/edit
i have developed a web application using kendo ui tools and theres a kendo grid with batch edit mode..
but when i press the delete button for any record in kendo grid it will erase from the list in grid but actually not in the data source.when i reload the page or grid the deleted item will still exist..
here is the code of my grid
<div id="grid">
</div>
<script type="text/javascript">
$("#submitMarketUser").click(function () {
var grid = $("#grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "WholeSaleTrade/GetTradeProductDetail",
dataType: "json",
data: {
test: $("#Names").val()
}
},
destroy: {
url: "WholeSaleTrade/DeletePro",
type: "POST",
dataType: "jsonp",
data: {
DAKy: $("#Names").val(),
DIKy: $("#btntxt").val()
}
},
create: {
url: "WholeSaleTrade/CreateProduct",
type: "POST",
dataType: "jsonp",
data: {
AKy: $("#Names").val(),
IKy: $("#btntxt").val()
}
}
},
pageSize: 5,
schema: {
model: {
id: "ProductKey",
fields: {
ProductKey: { editable: false, nullable: true },
ProductName: { validation: { required: true} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
editable: true,
toolbar: ["create", "save"],
autobind: true,
pageable: true,
columns: [
{ field: "ProductName", title: "Product Name",
editor: function (container, options) {
var model = options.model;
$('<input id="btntxt" name="' + options.field + '"/>').appendTo(container).kendoComboBox({
dataSource: {
type: "POST",
transport: {
read: {
url: "MarketInformation/PopulateProducts",
success: function (data) {
var prod = data[0];
model.set("ProductName", prod.ItmNm);
model.set("ItmKy", prod.ItmKy);
model.set("UserKey", $("#Names").val());
}
}
}
},
dataValueField: "ItmKy",
dataTextField: "ItmNm"
});
}
},
{ command: ["destroy"], title: " " }
]
});
});
</script>
can not identify that where is the fault going and can somebody please help me to solve this matter.
There are three common reasons delete won't work:
1. Not setting editable of grid to inline or popup. The deleted items will be automatically processed through transport destroy only for "inline"/"popup" edit modes. Ex:
editable: {
mode: "inline",
}
//or
editable: "inline"
2. If on your datasource, you have the batch flag set to true, this means the datasource will make the call only after you tell it to, e.g calling sync(). Ex:
var dataSource = new kendo.data.DataSource({
batch: true,
//.....
});
//... in some where e.g in a save button click event call the following line:
dataSource.sync();
3. You should define id to your primary key of database field name inside model of datasource. Ex:
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
}
}
So the problem with your code is first one, i.e you did not set editable to inline or popup
If you choose not to include editable.mode in order to utilize the in-cell editing, you can set the toolbar of the grid to include the option save:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
}
},
toolbar: ["create", "save", "cancel"],
columns: [
....
],
editable: true
});
This will create a save button at the toolbar of the grid. After deleting any records by clicking the destroy command button, click on the save button to have the grid to make an Ajax call to the server to delete the record.
If you would rather delete the record automatically without including the save button, you could add a change event handler to the datasource of the grid:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
},
change: function(e) {
if (e.action === "remove") {
this.sync();
}
}
},
columns: [
....
],
editable: true
});
This will automatically sync the changes you made to the grid with the server when there's a data change.
Hmm try not including type: "POST", and see if it now works since as far as I can see that bit isn't included on the demo's and I don't think I included it when I last did inline edits/deletes.
I had put an arbitray name for an int on the server Delete Method.
[HttpPost]
public ActionResult DeleteRandomTest(Int32 randomTestId)
{
...
}
The default modelbinder was probably looking for a property called Id (same as the primary key of my type according to the configuration of the model).
.Model(config => config.Id(p => p.Id))
In fact, I proved this by changing the signature to the following:
[HttpPost]
public ActionResult DeleteRandomTest(Int32 Id)
{
...
}
My break point was hit after that.
Ultimately, I used the full type as the parameter as shown in the Kendo examples because I didn't want to have poorly named parameter names (not camel case) in the action. Shown as follows:
[HttpPost]
public ActionResult DeleteRandomTest([DataSourceRequest]
DataSourceRequest request, RandomDrugTest randomDrugTest)
{
...
}
This seems to the be the reason it wasn't working.
I had the same issue. My issue was caused by having a data property in the kendo model. Example:
{id: 1, data: ""}
I have a geo collection that contains items like:
[state name]
[city], [state]
[country]
A text box is available for a user to begin typing, and a jQuery autocomplete box fills displays possible options.
The URL structure of the post request will depend on which was selected from the collection above, ie
www.mysite.com/allstates/someterms (if a country is selected)
www.mysite.com/city-state/someterms (if a city, state is selected)
www.mysite.com/[state name]/someterms (if a state is selected)
These are already defined in my routes.
I was initially going to add some logic on the controller to determine the appropriate URL structure, but I was thinking to simply add that as an additional field in the geo table, so it would be a property of the geo collection.
Here is my jQuery function to display the collection details when, fired on keypress in the textbox:
$(function () {
$("#txtGeoLocation").autocomplete(txtGeoLocation, {
source: function (request, response) {
$.ajax({
url: "/home/FindLocations", type: "POST",
dataType: "json",
selectFirst: true,
autoFill: true,
mustMatch: true,
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
document.getElementById("hidLocation").value = ui.item.id;
}
});
});
What I would like is to have structure the URL based on an object parameter (seems the simplest). I can only seem to read the parameters on "selected", and not on button click.
How can I accomplish this?
Thanks.
To resolve this, I removed the select: portion from the Javascript, and added the selected object parameters in the MVC route sent to my controller.