Kendo dataSource.add - "Id is not defined" - javascript

I'm trying to add some items to a Kendo DataSource to then display in the grid. However, every time I try to save I get Reference Error: Id is not defined.
At first I thought it was because I didn't include Id in my schema but I checked and it looks alright.
var viewModel = new kendo.observable({
orgDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Organization/GetAll",
dataType: "json"
},
update: {
url: "/Host/Organization/Edit",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
create: {
url: "/Host/Organization/Create",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
destroy: {
url: "/Host/Organization/Delete",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number", editable: false, nullable: true },
Name: { type: "string" },
LicenseExpiration: { type: "date" },
LicenseNumber: { type: "number" },
Active: { type: "boolean" },
CreateDate: { type: "date" },
LastModDate: { type: "date" },
AvailableLicenses: { type: "string" },
State: { type: "string" }
}
},
errors: "errorMsg"
},
pageSize: 20,
error: function (e) {
toastr.options = {
"positionClass": "toast-bottom-full-width"
};
toastr.error("There was an error: " + e.errors, "Uh, Oh!");
this.cancelChanges();
},
serverPaging: false,
serverFiltering: false,
serverSorting: false
}),
reloadOrganizations: function () {
this.get("orgDataSource").read();
},
onOrgSave: function (e)
{
var uid = $('input[name="OrgRowUID"]').val();
var tr = $('tr[data-uid="' + uid + '"]'); // get the current table row (tr)
var name = $('input[name="Name"]').val();
var licenseNumber = $('input[name="LicenseNumber"]').val();
var licenseExpiration = $('input[name="LicenseExpiration"]').val();
var email = $('input[name="Email"]').val();
var state = $('input[name="State"]').val();
var logo = $('input[name="ImageUrl]').val();
var active = $('input[name="Active"]').is(":checked");
// get the data bound to the current table row
var orgGrid = $("#OrganizationGrid").data("kendoGrid");
var data = orgGrid.dataItem(tr);
if (data == null)
{
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active })
orgGrid.saveChanges();
viewModel.orgDataSource.sync();
viewModel.reloadOrganizations();
} else {
data.set("Name", name);
data.set("LicenseNumber", licenseNumber);
data.set("LicenseExpiration", licenseExpiration);
data.set("Email", email);
data.set("State", state);
data.set("ImageUrl", logo);
data.set("Active", active);
}
$("#orgCreateModal").modal('hide');
$("#orgEditModal").modal('hide');
}
});
The error is occurring on this line:
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active });
The error in FireBug is:
Reference Error: Id is not defined - kendo.all.min.js line 25 > function

It's throwing that error because you're not setting "Id" to anything in your datasource. I had a similar problem a while back and Telerik said you have to give 'id' a valid unique value because they use that internally to keep things straight in the datasource. In your case, you are setting your schema id to "Id", but it doesn't look like your datasource has an "Id" field. I ended up just dumping a guid in there and it fixed my problem.

Related

KendoUI Grid Update Issue

I define a grid in my page :
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Grid/GetPerson",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'Get'
},
update: {
url: function (person) {
debugger;
return "/Grid/Update";
},
contentType: 'application/json; charset=utf-8',
type: "POST",
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number", editable: false, nullable: true },
Name: { validation: { required: true } },
Family: { validation: { required: true, min: 1 } },
Tel: {}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [
{ field: "Name", title: "نام" },
{ field: "Family", title: "فامیل" },
{ field: "Tel", title: "تلفن", width: "100px" },
{ command: [{ name: "edit", text: "ویرایش" }, { name: "destroy", text: "حذف" }], title: "عملیات", width: "160px" }],
messages: {
editable: {
cancelDelete: "لغو",
confirmation: "آیا مایل به حذف این رکورد هستید؟",
confirmDelete: "حذف"
},
commands: {
create: "افزودن ردیف جدید",
cancel: "لغو کلیه‌ی تغییرات",
save: "ذخیره‌ی تمامی تغییرات",
destroy: "حذف",
edit: "ویرایش",
update: "ثبت",
canceledit: "لغو"
}
},
editable: "popup"
});
});
In person parameter in update function, i can access changed row by :
person.models[0]
it gives me :
Object {ID:1,Name:"pejman",Family:"kam",Tel:"098787887"}
SO i want to send this data to the server, so i have a action in GridController:
[HttpPost]
public void Update(TblPerson person)
{
//do update
}
for doing it, i try :
url: function (person) {
return "/Grid/Update/" + JSON.stringify(person.models[0])
},
in the update method, but it doesn't work, how can i do it?
NOTE: when i using above in Network tab of browser give me Bad Reuest error:
URL:http://localhost:2145/Grid/Update/%7B%22ID%22:1,%22Name%22:%22pejman%22,%22Family%22:%22kam%22,%22Tel%22:%22098787878%22%7D
Status Code:400 Bad Request
The problem is that kendo.stringify(options.models) sends your object in JSON string. So I believe that your js code can stay as it is. Just change your Update method in controller to something like:
[HttpPost]
public void Update(string models)
{
var values = JsonConvert.DeserializeObject<IEnumerable<TblPerson>>(models);
foreach (var value in values)
{
//Your action
}
}
The approach above just assume that you can send more models to update. Don't forget using Newtonsoft.Json

Disable a Kendo-UI TreeView node

I have a TreeView and I want to disable some nodes when they contain in their data a state_current != null like the "disable node" button in the demo.
my code is :
<script>
$(document).ready(function() {
var treeview = $('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node)
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
}
var Matiere = {
transport: {
read: {
url: '#Url.Action("Get_Matiere")',
type: 'GET',
dataType: 'json'
}
},
schema: {
model: {
fields: {
name: 'Name',
type: 'matiere'
},
hasChildren: false,
}
}
}
var Session = {
transport: {
read: {
url: '#Url.Action("Get_Session")',
type: 'GET',
dataType: 'json'
}
},
schema: {
model: {
fields: {
id: 'IdPromo',
name: 'NamePromo',
type: 'session',
date: 'Date',
state: 'State_current',
},
hasChildren: true,
children: Matiere
}
}
}
var Parcours = {
transport: {
read: {
url: '#Url.Action("Get_Parcours", "Users")',
data: {user_id: #Model.id},
type: 'GET',
dataType: 'json'
}
},
schema: {
model: {
fields: {
id: 'Id',
name: 'Name',
type: 'parcours'
},
hasChildren: true,
children: Session
}
}
};
</script>
Do this where you want to disable the nodes
var selectedNode = treeview.select();
treeview.enable(selectedNode, false);
Here treeview should be your treeview object, you can select it as below once the treeview is created. And instead of selectedNode you can give the node which you need to disable.
var treeview = $('#Tree_view').data("kendoTreeView");
If you want to do this while the treeview renders first you can check this in kendoTreeView databound event, or in select event if you want it while selecting.

Values cannot pass from kendo grid to Entity class?

Here i my c sharp code of controller api class DefComapny whose value are always null while posting a data from kendo grid thats why not entering any thing to database?
[HttpPost]
public void SaveDefCompny()
{
var result = new List<DefCompany>();
using (var data = new RPDBEntities())
{
DefCompanyDTO productViewModel = new DefCompanyDTO();
var product = new DefCompany
{
//same problem of all entites getting no value from grid
Id = productViewModel.Id, // getting no value from grid
CurrentCurrencyCode = productViewModel.CurrentCurrencyCode,
ShortName= productViewModel.ShortName,
FullName= productViewModel.FullName,
ContactPerson= productViewModel.ContactPerson,
Address1= productViewModel.Address1,
CompanyCity= productViewModel.CompanyCity,
CompanyState= productViewModel.CompanyState,
CompanyCountry= productViewModel.CompanyCountry,
ZipPostCode= productViewModel.ZipPostCode,
TelArea= productViewModel.TelArea
};
result.Add(product);
data.DefCompanies.Add(product);
data.SaveChanges();
}
}
here is my viewmodel code
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { editable: true, type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create:{
url: "/api/Companies/SaveDefCompny",
dataType: "json"
},
update: {
url: "/api/Companies/SaveDefCompny", // here you need correct api url
dataType: "json"
},
destroy: {
url: "/api/Companies/Delete", // here you need correct api url
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
return kendo.stringify(data) ;
}
}
}
})
});
kendo.bind(document.getElementById("example"), viewModel);
}
how should i pass my inline kendo grid values to my controller so that it save it in database?
Check Kendo documentation and see what kind of parameters SaveDefCompny should expect. You should then be able to read whatever you require using those parameters.
url: "/api/Companies/SaveDefCompny", dataType: "json"
This most likely is sending your controller method the required data in json format.
Again: your answer lies in the Kendo documentation.
EDIT:
See this and this.
From their example:
public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Product
{
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Add the entity
northwind.Products.Add(entity);
// Insert the entity in the database
northwind.SaveChanges();
// Get the ProductID generated by the database
product.ProductID = entity.ProductID;
}
}
// Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}

How to add new tags in select2?

I am trying to get the tags from my api. Everything works fine but I cant able to add new tags. Here is what i tried:
$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});
By using the above code, I can only get the tags but I cant able to add the new tags. how can i add the new tags?
Please help
$("#e11_2").select2({
createSearchChoice: function(term, data) {
if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.

How to fill in checkbox in Backbone-form

im trying to fill a array checkboxes with other which came from a json array. my code is simple,
var cmyBox = Backbone.Collection.extend({
model: mmyBox,
url: 'http://localhost/wordpress/oferta/prueba1/?json=get_taxonomy&taxonomy=habilidad',
parse: function (resp) {
var skillsname = new Array();
var i = 0;
resp.terms.forEach(function(item) {
skillsname[i] = item.slug
i++
});
console.log(skillsname);
return skillsname;
}
});
var Form = Backbone.Model.extend({
schema: {
id: {},
nombre: {},
apellidos: {},
email: { type: 'Text', dataType: 'email', validators: ['required', validateEmail] },
telefono: { type: 'Text', dataType: 'tel', validators: ['required'] },
nacionalidad: { type: 'Select', options: ['Española', 'Extranjera'] },
link1: { type: 'Text', title: 'Enlace a Reel', dataType: 'url' },
link2: { type: 'Text', title: 'Enlace a Web/Blog', dataType: 'url' },
others: { type: 'Text', dataType: 'url' },
skills1: { type: 'Checkboxes', options: cmyBoxes },
}
});
var List = new Form ({
skills1: true
});
The problem is that the array is create and has what i need but its not where it would have to be. I dont know to assign the result of collection to that field. Maybe i m doing some wrong. Whtat i want to do is this:
skills1: { type: 'Checkboxes', options: ["artist", "medico", "programador"] },
Thanks
Well i found the solution, for someone who need it. Use the toString function, its very usefull...
var mmyBox = Backbone.Model.extend({
toString: function() { return this.get('slug'); }
});
var cmyBox = Backbone.Collection.extend({
model: mmyBox,
url: 'http://localhost/wordpress/oferta/prueba1/?json=get_taxonomy&taxonomy=habilidad',
parse: function (resp) {
return _.map( resp.terms, function( item ){
return {
id: item.id,
slug: item.slug
};
});
}
});

Categories

Resources