Navigating between Kendo Pages by using ID and showing data - javascript

I have 2 views in my MVC project From the View1 I am taking an ID and passing it to View2. On view2, I already have KendoGrid and I have controller that reads all data for me and display in grid.
My question is how to get data from ID in View2? I copied my script code of View2 below
var crudServiceBaseUrl = "http://localhost:23355/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
url: crudServiceBaseUrl + "/api/SpecificationDetails",
dataType: "json",
cache: false
},
update: {
// update code goes here
},
},
destroy: {
// delete code goes here
},
create: {
// create code goes here
},
parameterMap: function (options, operation) {
console.log(operation + '-' + options.models);
if (operation === "create" && options.models) {
options.models[0].SpexHeaderId = 5;
var jsonstr = JSON.stringify(options.models[0])
console.log(jsonstr);
return jsonstr;
}
else if (operation === "update" && options.models) {
var jsonstr = JSON.stringify(options.models[0])
console.log(jsonstr);
return jsonstr;
}
else if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 4,
schema: {
model: {
id: "SpecificationDetailId",
fields: {
SpecificationDetailId: { editable: false, type: "number" },
DescriptionTitle: "DescriptionTitle",
Description: "Description",
}
},
total: function (response) {
return response.total;
}
}
});

You are running jQuery 1.5.
Kendo UI requires a minimum of jQuery 1.7.1 (for Kendo UI 2011.3.1129). The current official version of Kendo UI (2017.2.504 (R2 2017)) requires jQuery 1.12.3.
Please refer to this chart for the specific version of jQuery that you require for your version of Kendo UI. You can grab a link to any version of jQuery from code.jquery.com.
If you are using legacy code, you'll additionally need to include jQuery Migrate.
Hope this helps! :)

Related

Unable to load the dropdown list on a kendo window from a method using Webservice

On clicking Edit button on a Page a method is triggered and a window which uses a kendo template is opened . One of the control on the kendo window is Kendo dropdown list which needs to have values comming from the webmethod.The error i am getting on clicking of the edit button is 'Object doesn't support property or method 'slice'. Below is my code for the Edit button.
function edit(item) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node}))
.appendTo("body")
.kendoWindow({
modal: true,
activate:function(){
$("#roles").kendoDropDownList({
dataTextField: "Countryname",
dataValueField: "CountryId",
dataSource: {
transport: {
read: {
url: "/Services/MenuServices.asmx/getcountries",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
}
}
}
})
},
deactivate: function () {
this.destroy();
}
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var Id = $('#ID').val();
node.set("id", Id);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("id", Id);
treenode.ID = Id;
console.log(JSON.stringify(treenode));
})
}
IS there any property for Kendo window that triggers this service when its opened.Right now i am using activate event but its not working.tried using 'Open' event also.
Thanks
I added the Schema part to the datasource and it worked.
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: { // define the model of the data source. Required for validation and property types.
id: "CountryId",
fields: {
CountryId: { editable: false, nullable: false, type: "string" },
Countryname: { editable: true, nullable: true, type: "string" },
}
},
},

extjs store sometimes calling create instead of update

We have the following store in ExtJS 4.2:
Ext.define('Example.store.BasketDocuments', {
extend: 'Ext.data.Store',
model: 'Example.model.Document',
autoLoad: true,
autoSync: true,
sorters: [
{
property: 'doc_type',
direction: 'ASC'
}
],
proxy: {
type: 'rest',
url: baseUrl + 'document_basket',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=utf-8'
},
reader: {
type: 'json',
root: 'items'
},
writer: {
type: 'json'
},
actionMethods: {create: "POST", read: "GET", update: "PUT", destroy: "DELETE"}
}
});
It is attached to a grid with drag and drop functionality.
When we drag around 10 files (for 9 it works) to the grid which would immediately update the store, we get a server error, because we do not implement the POST function for URLs like
/api/document_basket/1964?_dc=1459498608890&{}
This is only for one entry.
For the others it would be
/api/document_basket?_dc=1459498608941&{}
which works.
Dragging only that single entry works.
So ExtJS is sending a POST request with an ID in the URL, which should be a PUT instead? Why is that?
I was able to fix this in my project.
Reason was that I was adding items to the store in a loop - so after each add of - let's say 14 files - a sync was done.
I discovered that there were 105 requests, which is just 1+2+3+4+5+6+7+8+9+10+11+12+13+14 so this caused a race condition.
Solution is to disable syncing before the loop:
onBeforeDropItem: function (node, data, overModel, dropPosition, dropHandlers, eOpts) {
dropHandlers.cancelDrop();
var store = Ext.getStore('BasketDocuments');
store.suspendAutoSync(); // new
if (node.id != 'documenttreepanel-body') {
Ext.Array.each(data.records, function (r, index) {
r = r.copy();
r.phantom = true;
r.data.id = null;
r.data.download_size = 1;
r.data.download_type = 1;
if (r.data.doc_type == 1) {
if (r.data.count == 0) {
Ext.create('Ext.window.MessageBox').show({
title: Ext.ux.Translate.get('Info'),
msg: Ext.ux.Translate.get('Ordner') + '<b>' + r.data.name + '</b>' + Ext.ux.Translate.get(' Is empty and cannot be added ') + '.',
buttons: Ext.Msg.OK,
modal: true
});
} else {
store.add(r);
}
} else {
store.add(r);
}
});
}
store.sync(); // new
store.resumeAutoSync(); // new

Properly Initialize Client Side Model

My issue is very simple. I am using ASP Web API, Entity Framework, Angular, and Kendo UI. I have 2 classes, FREQUENCY and FREQ_TYPE_. Class FREQUENCY has a navigation property to class FREQ_TYPE. I have a kendo ui grid that loads 10 class FREQUENCY models. Each class FREQUENCY model has it's FREQ_TYPE data loaded properly. My problem is that when I create a new row in my kendo ui grid and try to save the row to the server, I get an error saying the navigation property FREQ_TYPE needs to be initialized. This is expected of course since kendo doesn't know how to auto=initialize my nav properties.
What is the best practice for giving my angular JS client the knowledge it needs to create a new class FREQ_TYPE so I can properly initialize class FREQUENCY and save it to the server? My models only exist as code-first entity models, so I can't just create a new model in my client side JS as it doesn't know about these models. Is there some framework that can generate local model classes from an EF database? Or do I just have to manually set all the json fields for my class FREQ_TYPE navigation property? Or is there an easier way for me to use Web API so that I can make a request to "figure out" what the model info is and create a client side JS model without needing to have a "local model"?
Here is the client side grid and datasource:
$(document).ready(function () {
var crudServiceBaseUrl = "http://localhost:29858/";
var NIICDDS = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "api/NIICDFreq",
dataType: "json"
},
update: {
url: function (data) {
console.log("DATA TEST");
console.log(data);
return crudServiceBaseUrl + "api/NIICDFreq/";
},
// url: crudServiceBaseUrl + "api/VHFMasterLists",
dataType: "json",
data: function (data) {
console.log("returning data in update TEST");
console.log(data.models[0]);
return data.models[0];
},
type: "PUT",
contentType: "application/json; charset=utf-8",
},
destroy: {
url: crudServiceBaseUrl + "api/NIICDFreq",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "api/NIICDFreq",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8"
},
parameterMap: function (model, operation) {
if (operation !== "read" && model) {
return kendo.stringify(model);
} else {
return kendo.stringify(model) ;
}
}
},
batch: true,
pageSize: 20,
schema: {
data: function (data) { //specify the array that contains the data
console.log("DATA RETURN TEST");
console.log(data);
return data || [];
},
model: {
id: "Id",
fields: {
Id: { editable: false,
nullable: false,
type: "number"
},
Frequency: { type: "string" }
}
}
}
});
$("#NIICDFreqGrid").kendoGrid({
dataSource: NIICDDS,
columns: [
{ field: "Id", title: "Freq ID", format: "{0:c}", width: "120px" },
{ field: "Frequency", title: "Frequency Test", format: "{0:c}", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }
],
toolbar: ["create"],
editable: "inline"
});
});
And here is the web api controller:
[ResponseType(typeof(FREQUENCY))]
public IHttpActionResult PostFREQUENCY(FREQUENCY testfreq)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.FREQUENCIES.Add(testfreq);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (FREQUENCYExists(testfreq.Id))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = testfreq.Id }, testfreq);
}
The error is the last line:
iisexpress.exe Information: 0 : Request, Method=POST, Url=http://localhost:29858/api/NIICDFreq, Message='http://localhost:29858/api/NIICDFreq'
iisexpress.exe Information: 0 : Message='NIICDFreq', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='CFETSWebAPI.Controllers.Frequency.NIICDFreqController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='CFETSWebAPI.Controllers.Frequency.NIICDFreqController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'PostFREQUENCY(FREQUENCY testfreq)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Message='Value read='DomainModelModule.FREQUENCY'', Operation=JsonMediaTypeFormatter.ReadFromStreamAsync
iisexpress.exe Information: 0 : Message='Parameter 'testfreq' bound to the value 'DomainModelModule.FREQUENCY'', Operation=FormatterParameterBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Message='Model state is invalid.
testfreq.FREQ_POOL: The FREQ_POOL field is required.,testfreq.FREQ_TYPE: The FREQ_TYPE field is required.', Operation=HttpActionBinding.ExecuteBindingAsync
And of course testfreq has all null values.
Thank you for your help.
Since you shared no code, I can only make an assumption. However, I think you're confused with the error message. Neither Kendo or Angular are responsible. They do not "initialize" classes. You said yourself, the data is there on the client.
From what it sounds like to me, the data arrives at your controller action, and the compiler does not know how to initialize your class. Make sure your Class B has a constructor defined in your server-side code. Even an empty constructor will suffice, unless the members of the class need explicit initialization themselves.
public class B {
// constructor
public B() {
// initialize class members
}
}

Kendo Grid CRUD: how make update

i have a kendo ui grid with asp web api as backend. When i call the create method in the kendo ui, it's called the following method in web api
public IHttpActionResult PostProduct(ProductDTO product)
{
...
...
return StatusCode(HttpStatusCode.NoContent);
}
Now if i try to edit the item in the Kendo Ui Grid is called again the create method instead of the update method.
If i reload the page (so is called the read method of kendo ui grid), the update method works.
What's the problem? I have the following schema:
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, type: "number" },
Name: { validation: { required: true } },
Description: { editable: true },
Price: { editable: true },
Active: { type: "boolean" },
}
}
}
I have the following transport (omitted some code)
$scope.tabellaProdotto = new kendo.data.DataSource({
transport: {
read: {
url: function () {
return "api/Prodotti/GetProdottoPerTipoProdotto/" + productTypeMainSelected;
},
dataType: "json"
},
create: {
url: "api/Prodotti/PostProdotto",
dataType: "json",
data: function (prodottoTmp) {
...
},
type: "POST"
},
update: {
url: function (prodotto) {
return "api/Prodotti/PutProdotto" + prodotto.Id
},
data: function (prodottoTmp) {
...
},
type: "PUT",
dataType: "json"
UPDATE: the problem seems be the return of the web api action method:
return CreatedAtRoute("DefaultApi", new { id = p.Id }, p);
Now works but the p object size dimension is very high: i must return the entire object?
This sounds like the Grid is not getting the Json back in the right format.
Be sure to use the KendoMVC DataSourceRequest Object to return data in the right format.
Here is an example:
public ActionResult Update([DataSourceRequest] DataSourceRequest request, MyViewModel data)
{
var result = UpdateBackend(data);
return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

Kendo DataSource appends Schema Id on datasoure sync

Just want to know why push method of the javascript inserts "index"
var agendaBatch=[];
for(var i=0; i<agendas.length; i++) {
var agenda = {
MeetingId: meetingId,
Title: agendas[i].title,
Description: agendas[i].description,
Remarks: "",
};
agendaBatch.push(agenda);
}
console.log(kendo.stringify(agendaBatch));
dataSourceAgenda.add(agendaBatch);
dataSourceAgenda.sync();
output:
{"0":{"Title":"Agenda title","Description":"Agenda details","Remarks":""},
"1":{"Title":"Agenda title","Description":"Agenda details","Remarks":""}}
what I expect is this output to match my Web API parameter requirement
[{"Title":"Agenda title","Description":"Agenda details","Remarks":""},
{"Title":"Agenda title","Description":"Agenda details","Remarks":""}]
Any suggestions how can I do this?....
UPDATE: just found out a moment ago, I'm using kendo ui datasource, I fixed the problem when I removed the Id on the schema
var dataSourceAgenda = new kendo.data.DataSource({
transport: {
type: "odata",
create: {
type: "POST",
url: API_URL + "/agendas",
contentType: "application/json; charset=utf-8",
dataType: 'json'
},
parameterMap: function (options, operation) {
if (operation !== "read" && options) {
return kendo.stringify(options);
}
}
},
schema: {
model: {
id: "Id", //I get my desired output if this is removed
fields: {
MeetingId: { type: "number" },
Title: { type: "string" },
Description: { type: "string" },
Remarks: { type: "string" },
}
},
}
});
HOWEVER I need to the Id parameter in other functions, is there anyway I can do this without removing the Id in kendo datasource.
Changed the Question title!
According the documentation of Kendo UI DataSource (here), add method accepts an Object not an array of Object.
In addition, you use as id a field called Id that is not among the fields of your model.
Try doing the following:
var dataSourceAgenda = new kendo.data.DataSource({
transport: {
create : function (op) {
...
},
parameterMap: function (options, operation) {
if (operation !== "read" && options) {
return kendo.stringify(options.models);
}
}
},
batch : true,
schema : {
model: {
id : "Id", //I get my desired output if this is removed
fields: {
Id : { type: "number" },
MeetingId : { type: "number" },
Title : { type: "string" },
Description: { type: "string" },
Remarks : { type: "string" }
}
}
}
});
I.e.:
Set batch to true for being able to send multiple requests at a time when you invoke sync.
Define Id in the schema.model.fields definition.
Do the stringify of options.models.
As agendaBatch is obviously an array, I assume that kendo.stringify is not serializing it properly. You could go with JSON.stringify.
Note that this is not implemented by older browsers. If you need to support them, you could include the script by Douglas Crockford:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
EDIT
Now that you changed your question - I am not really familiar with kendo ui, so this really is just a wild guess in an attempt to help you with your updated problem.
It looks like you have access to the data in the beforeSend function. You could try to manipulate it for your needs, like this maybe:
beforeSend: function (xhr, s) {
var arrayData = [];
for (var id in s.data) {
arrayData.push(s.data[id]);
}
s.data = arrayData;
}

Categories

Resources