Fetch id in kendo ui grid - kendo-ui

I had this schema in my kendo-ui datasource. Then I had custom button in my kendo grid located at (column > field), so my question how to get an id when I click on that custom button? I try
click: function(e) {
e.preventDefault();
var currentId = $(e.target).closest("venueConfigurationTypeID");
var id = this.dataItem(currentId);
//var item = this.dataItem.id; <-- return undefined
}
and it return me a null value.
....
schema: {
model: {
id: "venueConfigurationTypeID",
fields: {
venueConfigurationTypeID : { editable: false, nullable: true },
configurationType : { type: "string", validation: {required: {message: "Value Required"}}},
configurationTypeDescription : { type: "string", validation: {required: {message: "Value Required"}}}
}
}
},
....

Find the answer.
click: function(e) {
e.preventDefault();
var selection = $(e.target).closest("tr");
var rowData = grid.dataItem(selection);
var id = rowData.venueConfigurationTypeID;
console.log(id);
}

Related

Using fetch method inside Kendo UI grid.template

How to return value from .fetch() method inside grid.template ?
$("#grid-single-user-groups").kendoGrid({
dataSource: assignedUsersDataSource,
toolbar: ["create"],
columns: [
{
field: "UserID", width: "100%",
editor: userDropDownEditor,
template: function(userID) {
//here I can return everything, and its visible in grid cell
//return "BAR"
allUsersDataSource.fetch(function() {
//Here everything is UNDEFINED
return "FOO";
var data = this.data();
console.log(data.length);
for (var idx = 0, length = data.length; idx < length; idx++) {
console.log(data.length); //show right length
console.log(data[idx].UserName);// //show right UserName
if (data[idx].UserNameID === userID.UserID) {
return userID.Login; //UNDEFINED
//return "foo"; //UNDEFINED
}
})
edit:
allUsersDataSource is Kendo DataSource:
var allUsersDataSource = new kendo.data.DataSource({
transport: {
read: {
url: API_URL + "frank/getusers",
dataType: "json"
}
},
});
results JSON:
[{"UserNameID":"2","UserName":"foo","Surname":"foo2","Login":"foo3","GroupName":"admin"},]
edit2:
trying with read() function instead od fetch, with below code:
template: function(userID) {
allUsersDataSource.read().then(function() {
var view = allUsersDataSource.view();
console.log(view[0].Login)// displays right Login
return view[0].Login; // displays "undefined" in grid cell
});
}
edit3:
My entire code where I whant to use DropDown inside Grid cell:
var allUsersDataSource = new kendo.data.DataSource({
transport: {
read: {
url: API_URL + "frank/getusers",
dataType: "json"
}
},
});
allUsersDataSource.fetch(function() {
allUsers = allUsersDataSource.data();
})
var assignedUsersDataSource = new kendo.data.DataSource({
transport: {
read:{
url: API_URL+"frank/getassignedusers/"+documentId,
dataType: "json"
},
create: {
type: "POST",
url: API_URL+"frank/addusertodocument",
dataType: "json"
},
destroy:{
type: "POST",
url: API_URL+"frank/removeuserdocument",
dataType: "json"
},
},
pageSize: 4,
schema: {
model: {
fields: {
UserName: { editable: false, nullable: true },
Surname: { editable: false, nullable: true },
UserID: { field: "UserID", defaultValue: 1 },
GroupName: { editable: false, nullable: true },
}
}
}
});
$("\#grid-single-user-groups").kendoGrid({
dataSource: assignedUsersDataSource,
filterable: true,
scrollable: false,
toolbar: ["create"],
pageable: true,
columns: [
{
field: "UserID", width: "100%",
editor: userDropDownEditor,
title: "Agent",
template: function(userID) {
for (var idx = 0, length = allUsers.length; idx < length; idx++) {
if (allUsers[idx].UserNameID === userID.UserID) {
return userID.Login;
}
}
}
},
{ command: "destroy" }
],
editable: true,
remove: function(e) {
console.log("Removing", e.model.name);
}
});
function userDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Login",
dataValueField: "UserNameID",
filter: "contains",
dataSource: allUsersDataSource
})
}
JSON DataSources - assignedUsersDataSource:
[{"UserID":"198","UserName":"Paw","Surname":"yui","Login":"ddz","GroupName":"ddd"},...]
JSON DataSources - allUsersDataSource:
[{"UserNameID":"198","UserName":"Paw","Surname":"yui","Login":"ddz","GroupName":"ddd"},...]
edit4:
corrected sample datasource:
var assignedUsersDataSource = new kendo.data.DataSource({
data: [{"UserID":"198","UserName":"Paw","Surname":"Mu","Login":"pc","GroupName":"ad"}]
});
var allUsers = new kendo.data.DataSource({
data: [{"UserNameID":"198","UserName":"Paw","Surname":"Mu","Login":"pc","GroupName":"ad"},{"UserNameID":"199","UserName":"Jakub","Surname":"Ch","Login":"jc","GroupName":"ki"}]
});
So to avoid cluttering up the comments here is a possible answer to your problem:
http://dojo.telerik.com/INukUVoT/4
If you now select the item from the dropdown it is changing the id as it retains the last selected item in the selection when you go in and out of it. The reason the name stays the same is a simple one. It's looking in the wrong place for the value to display.
You are simply doing the following:
Look at all the values in the allusers store and then if i get a match of id's just show the value in the model's Login value rather than the value that was found in the data item in the Login.
So you are currently going through a needs loop. you literally could change your template to:
template: "#=data.Login#" rather than having to loop around.
what you seemingly want to do is have one column which is a user object or defined as an id either way will work as you can see in my new examples.
the first grid is binding the UserID property to the grid and then presenting back the value from the dropdown's datasource (you need to ensure that you set the valuePrimitive property to true so it binds only the value and not the object.
the second grid binds the full object and just so you see what is being bound i am stingify'ing the object and putting that into the grid.

Kendo treeview HierarchicalDataSource not showing child nodes

I have a kendo Treeview which is showing the parent nodes but the child nodes are not seen. Can anyone tell me where am i going wrong. I am new to this concept. I followed the below link but its not working.
http://demos.telerik.com/kendo-ui/treeview/remote-data-binding
function treeView() {
var treeM = new kendo.data.HierarchicalDataSource({
schema: {
data: function (response) {
console.log("response" + JSON.stringify(response));
var rdata = {};
if (response.d) {
rdata = JSON.parse(response.d);
}
else {
rdata = response;
}
return rdata; // ASMX services return JSON in the following format { "d": <result> }.
},
model: {
hasChildren: true,
id: "ID",
expanded: true,
fields: {
ID: { editable: false, nullable: false, type: "string" },
LINK: { editable: true, nullable: true, type: "string" },
},
},
},
transport: {
read: {
url: "/getParent",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
parameterMap: function (data, type) {
if ((type == "update") || (type == "create") || (type == "destroy")) {
console.log('parameterMap:');
return JSON.stringify({ "LinksJson": data });
console.log(JSON.stringify(data));
} else {
return data;
}
}
}
});
$("#treeview1").kendoTreeView({
dataSource: treeM,
dataValueField: "ID",
dataTextField: ["LINK","Name"]
});
}
$("#treeview").on("click", ".k-in", function (e) {
var tree = $("#treeview").data('kendoTreeView');
tree.toggle($(e.target).closest(".k-item"));
});
$(document).ready(function () {
treeView();
});
Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getParent()
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in context.Links
where x.ParentID == 68
select x;
var newQry = dataQuery.AsEnumerable().Select(c => new
{
ID = c.ID,
Name = c.Name,
Children = HasChildren(231)
});
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(newQry);
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool HasChildren(int ID)
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in contextLinks
where x.ParentID == ID
select x;
return dataQuery.AsEnumerable().Any();
}
}
Even when you try to view the child nodes, it will try to call getLinks and not the getreports.
From what i have seen , you should have only one method for getting parent and children. Can be an array inside each parent node.
Can you combine the data from GetReports method inside getlinks itsself and give it a shot.
You should try and get this working here with hardcoded values and then do configure with services.
http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#configuration-dataSource

Kendo UI Grid posting back already Inserted Rows again

I am running into problem, where when an Insert is completed successfully and if i continue to insert another row, in the next insert it is also sending the row that was inserted successfully earlier, so it goes like this.
On the First insert that row is posted back to webAPI and inserted successfully.
On Next Insert Two rows are sent one of them was from first step.
On third Insert it send previous two rows as well as third row and so on.
What could be the cause of this ?
This is the Code in problem.
$(document).ready(function () {
try {
var degreeYearsArray = new Array();
function GetDegreeName(dgID, degreeName) {
for (var i = 0; i < degreeYearsArray.length; i++) {
if (degreeYearsArray[i].dgID_PK == dgID) {
return degreeYearsArray[i].Name;
}
}
return degreeName;
}
var degreeYearModel = {
id: "DGYR_PK",
fields: {
DGID_FK: {
type: "number",
nullable: false,
editable: false
},
Code: {
type: "string",
validation: {
required: true,
minlength: 2,
maxlength: 160
}
},
Year: {
type: "number",
validation: {
required: true
}
},
EffectiveDate: {
type: "date",
validation: true
},
TerminationDate: {
type: "date",
validation: true
}
}
};
var baseURL = "http://localhost:3103/api/Degree";
var degreeYearTransport = {
create: {
url: baseURL + "/PostDegreeYears", // "/PutOrgSchool",
type: "POST",
// contentType: "application/json"
dataType: "json"
},
read: {
url: function () {
var newURL = "";
if (window.SelectedDegree == null)
newURL = baseURL + "/GetDegreeYears"
else
newURL = baseURL + "/GetDegreeYears?degreeID=" + window.SelectedDegree.DGID_PK;
return newURL;
},
dataType: "json" // <-- The default was "jsonp"
},
update: {
url: baseURL + "/PutDegreeYears", //"/PostOrgSchool",
type: "PUT",
// contentType: "application/json",
dataType: "json"
},
destroy: {
url: function (employee) {
return baseURL + "/deleteOrg" + employee.Id
},
type: "DELETE",
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
try {
if (operation != "read") {
options.EffectiveDate = moment(options.EffectiveDate).format("MM-DD-YYYY");
options.TerminationDate = moment(options.TerminationDate).format("MM-DD-YYYY")
}
var paramMap = kendo.data.transports.odata.parameterMap(options);
delete paramMap.$format; // <-- remove format parameter.
return paramMap;
} catch (e) {
console.error("Error occure in parameter Map or Degree.js" + e.message);
}
}
}; //transport
var dsDegreeYears = new kendo.data.DataSource({
serverFiltering: true, // <-- Do filtering server-side
serverPaging: true, // <-- Do paging server-side
pageSize: 2,
transport: degreeYearTransport,
requestEnd: function (e) {
try {
if (e.type == "update"){
$.pnotify({
title: 'Update Sucessful',
text: 'Record was Updated Successfully',
type: 'success'
});
}
if (e.type == "create") {
$.pnotify({
title: 'Insert Sucessful',
text: 'Record was Inserted Successfully',
type: 'success'
});
}
} catch (e) {
console.error("error occured in requestEnd of dsDegreeYears datasource in DegreeYears.js" + e.message);
}
},
schema: {
data: function (data) {
return data.Items; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.Count; // <-- The total items count is the data length, there is no .Count to unpack.
},
model: degreeYearModel
}, //schema
error: function (e) {
var dialog = $('<div></div>').css({ height: "350px", overflow: "auto" }).html(e.xhr.responseText).kendoWindow({
height: "300px",
modal: true,
title: "Error",
visible: false,
width: "600px"
});
dialog.data("kendoWindow").center().open();
},
});
$("#" + gridName).kendoGrid({
dataSource: dsDegreeYears,
autoBind: false,
groupable: true,
sortable: true,
selectable: true,
filterable: true,
reorderable: true,
resizable: true,
columnMenu: true,
height: 430,
editable: "inline",
toolbar: ["create"],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [ {
field: "DGID_FK",
title: "Degree Name",
width: 140,
template: function (dataItem) {
if (window.SelectedDegree != null) {
dataItem.DGID_FK = window.SelectedDegree.DGID_PK;
return window.SelectedDegree.Name;
}
else
return "";
}
},
{
field: "Code",
title: "Code",
width: 140
},
{
field: "Year",
title: "Year",
width: 140
},
{
field: "Description",
width: 110
},
{
field: "EffectiveDate",
width: 110,
format: "{0:MM/dd/yyyy}"
},
{
field: "TerminationDate",
width: 110,
format: "{0:MM/dd/yyyy}"
},
{
command: ["edit"] , title: " ", width: "172px"
}
]
}); //grid
//Hide history pull-down menu in the top corner
$.pnotify.defaults.history = false;
$.pnotify.defaults.styling = "bootstrap";
// styling: 'bootstrap'
//styling: 'jqueryui'
} catch (e) {
console.error("Error occured in DegreeYears" + e.message);
}
}); // document
This is the Response that is sent from WebAPI
{"$id":"1","DGYR_PK":27,"DGID_FK":64,"Year":4,"Code":"4THYR","EffectiveDate":"2014-01-11T00:00:00","TerminationDate":"2014-01-11T00:00:00","CreatedByUserID_FK":1,"DateCreated":"0001-01-01T00:00:00","UpdatedByUserID_FK":1,"DateUpdated":"0001-01-01T00:00:00","RowStatusID_FK":1,"Degree":null,"DegreeYearExamSchedules":[],"User":null,"RowStatu":null,"User1":null,"DegreeYearSubjects":[]}
So i do see i am returning ID as suggested by the users in response to the question.
still wondering
After you have inserted a record, you need to return the id of that row, otherwise grid consider the previous row as a new row too.
In your create function you call the web API
baseURL + "/PostDegreeYears", // "/PutOrgSchool",
In the server side consider the below code.
public void Create(ABSModel model)
{
try
{
using (context = new Pinc_DBEntities())
{
tblAB tb = new tblAB();
tb.ABS = model.ABS;
tb.AreaFacility = model.AreaFacility;
context.tblABS.Add(tb);
Save();
model.ABSID = tb.ABSID;//this is the important line of code, you are returning the just inserted record's id (primary key) back to the kendo grid after successfully saving the record to the database.
}
}
catch (Exception ex)
{
throw ex;
}
}
please adjust the above example according to your requirement.
This will happen if you don't return the "DGYR_PK" value of the newly inserted model. The data source needs a model instance to have its "id" field set in order not to consider it "new". When you return the "ID" as a response of the "create" operation the data source will work properly.
You can check this example for fully working Web API CRUD: https://github.com/telerik/kendo-examples-asp-net/tree/master/grid-webapi-crud
Here is the relevant code:
public HttpResponseMessage Post(Product product)
{
if (ModelState.IsValid)
{
db.Products.AddObject(product);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.ProductID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Your primary key cannot be 0 or null. If you are using auto-incrementing values then you should invoke the "re-read" of your dataSource after post. Check the values and make sure your data values are >0. Note: I have set the default value of the PK in the model to -1 in the column model to help with this.
You can attached and respond to the requestEnd event on the DataSource.
requestEnd: function(e) {
if (e.type === "create") {
this.read();
}
}
What that is saying is: "After you created a record, reread the entries (including the newly created one) into the grid". Thereby giving you the newly created entry with key and all. Of course you see that the extra read may have some performance issue.

kendo ui listview selected item index

i have a div defined for my listview like this:
<div id="carrierList"></div>
Here is my script that defines the listview and its datasource ;
<script type="text/javascript">
$(document).ready(function () {
var t94StragglerCarriers = new kendo.data.DataSource({
transport: {
read: {
url: "/MenuTrain/T94StragglerCarriers",
dataType: "json"
},
schema: {
fields: {
id: { type: "string" },
val: { type: "string" }
}
},
pageSize: 5,
serverPaging : true
}
});
var carriers = $("#carrierList").kendoListView({
dataSource: t94StragglerCarriers,
selectable: true,
pageable : true ,
change: onChange,
template : kendo.template($("#carrierTemplate").html())
}).data("kendoListView");
function onChange() {
var index = carriers.select().index();
var item = carriers.dataSource.view()[index];
console.log("Item " + index + " selected. Guid = " + item.id);
}
});
Here is the template definition for my listview :
<script type="text/x-kendo-tmpl" id="carrierTemplate">
<div id='carrierListVal_#=val#_#=id#' class='k-textbox'>#=val#</div>
<br/>
Here is the action method on my controller :
public JsonResult T94StragglerCarriers( [DataSourceRequest] DataSourceRequest request)
{
return Json(t94RailcarRepository.CarriersWithStragglers(), JsonRequestBehavior.AllowGet);
}
Here is the json string returned by the server :
[{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"CHTT"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"CMO "},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"CTCX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"DBUX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"GATX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"MWCX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"NDYX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"PLMX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TAEX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TCIX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TEIX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"TILX"},{"id":"10eac72a-d62d-434f-8505-4869cdb27b04","val":"UP "},{"id":"ffbcdb6c-4d3a-45f6-8ef6-ada5f28ba44b","val":"MDXx"}]
My problem is that from the onChange event handler, when i try to get the index of the selected listview item, like so :
var index = carriers.select().index();
it is returned a value as if each field in the json string is an element. For example , the first object's id field would be index 0 , and it's val fiedl would be index 1. and so on. Can anyone see what i am doing wrong to get the index of the selected listview item? or is there something wrong with the json string i don't see?

keep the Ids of selected results of Kendo UI Autocomplete in a hidden input

I wrote this code to use kendo UI autocomplete. I need to show the title of the selected result in the textbox and keep the if in some hidden input, how can I get the id. it seems the select doesn't work.
$("[data-autocomplete]").each(function () {
var luurl = $(this).attr('data-lookupurl');
var thisElemt = $(this);
$(this).kendoAutoComplete({
minLength: 3,
separator: ", ",
dataTextField: "title",
select: function (e) {
var selectedOne = this.dataItem(e.item.Index());
console.log(kendo.stringify(selectedOne));
},
dataSource: new kendo.data.DataSource({
serverFiltering: true,
serverPaging: true,
pageSize: 20,
transport: {
read: luurl,
dataType: "json",
parameterMap: function (data) {
return { title: thisElemt.val() };
},
schema: {
model: {
id: "id",
fields: {
id: { type: "id" },
title: { type: "string" }
}
}
}
}
})
});
});
There is a typo error, you should use: e.item.index() instead of e.item.Index() (index is lowercase).
So the select function would be:
select : function (e) {
var selectedOne = this.dataItem(e.item.index());
console.log(kendo.stringify(selectedOne));
},
and easier way is :
var autocomplete = $("#autoCompleteId").data("kendoAutoComplete");
console.log(autocomplete.listView._dataItems[0]);
you can access to select data item in autocomplete.listView._dataItems[0] object
you can use script
<script>
$(document).ready(function () {
$("#categories").change(function () {
var url = '#Url.Content("~/")' + "Limitations/ThanaByDistrict_SelectedState";
var ddlsource = "#categories";
var ddltarget = "#target";
$.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$(ddltarget).val(data);
});
});
});
</script>
in controller like
// Get selected combox value
public JsonResult ThanaByDistrict_SelectedState ( Guid Sel_StateName )
{
JsonResult result = new JsonResult ( );
objects temp=db . objects . Single ( m => m . ob_guid == Sel_StateName );
result . Data = temp.ob_code;
result . JsonRequestBehavior = JsonRequestBehavior . AllowGet;
return result;
}
For details you can see this LINK

Resources