Kendo grid read datasource with http post response - angularjs

I am new at Kendo UI, I was using datatables to show values,here is my old code (Working):
$http.post("/reports/api/g3swmf/report", $scope.g3sWmf ).success(function(data){
$scope.reportVal += " - " + data;
}).then(function (response){
$scope.items=response.data;
}
And here is Kendo UI version (not Working):
$scope.g3sGridOptions = {
toolbar: ["excel"],
excel: {
allPages: true
},
dataSource: {
type: "json",
transport: {
read: {
url:("/reports/api/g3swmf/report", $scope.g3sWmf ),
type: "post",
dataType: "json"
}
},
schema: {
model: {
fields: {
poloCode: { type: "string" },
}
}
}
}

The kendo's transport url is suppose to be a string.
url:"/reports/api/g3swmf/report"
It doesn't handle the same the $http.post does. In fact, it pass the read parameter directly to jquery.ajax.
There's 2 way to solve this.
Use a string url for your transport
Define your transport.read as a function. You'll then be able to call you're own $http.post. If you define a function, note that kendo will provide a event parameter with some callback methods that should be used to send the data back to the grid.
Here's a custom read example:
read: function (readOptions) {
$http.post("/reports/api/g3swmf/report", $scope.g3sWmf ).success(function(data){
readOptions.success(data);
})
}
Please refer to kendo dataSource API documentation for more details

Related

Accessing additional properties from JSON received through store's load method

I have a grid that loads data via a JSON store, however there are some additional properties beyond the records themselves that I need to access. Here's an example of what the JSON data looks like:
{
success: true,
records: [
{id: 1, name: 'bob'},
{id: 2, name: 'fred'}
],
extraProperty: 'foo'
}
I need to access that extraProperty when the grid data is loaded. So I assume I'd want to a callback, like so:
store.load({
callback: function (records, operation, success) {
//somehow access extraProperty here
}
});
I'm not sure what to do inside that callback. The operation variable, an Ext.data.operation.Operation object, has a private method called getResponse(). It returns an object in Chrome that has a responseJson property, but in IE it instead has a responseText property that needs to be decoded. So I could handle both scenarios, but since it's a private method I don't really want to rely on it in the first place. Any ideas?
Use the keepRawData config on the reader.
store.load({
callback: () => {
const { extraProperty } = store.getProxy().getReader().rawData;
}
});
Depending on your needs, you may also want to look at preserveRawData as well.
did you tried on the store level, something like below
under proxy in the reader config section
proxy: {
type: 'ajax',
actionMethods: {
read: 'GET'
},
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
api: 'your url',
reader: {
extraProperty: 'extraProperty'
}
}

How to send form data from Angularjs to Django

I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]).
With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem.
$scope.saveUser = function(event) {
postForm({ id: 0 }, $('#FormName'), $scope, function(data) {
})
}
function postForm(postInfo, form, $scope, callback,) {
var postData = new FormData(form.get(0));
$.each(postInfo, function(key, value) {
postData.append(key, value);
});
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: postData,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
headers: {
"X-CSRFToken": app.getStorage("csrftoken")
},
beforeSend: function() {
$('#loading-image').show();
},
complete: function() {
$('#loading-image').hide();
if(typeof saveButtonId !== typeof undefined) {
$('#'+saveButtonId).removeAttr('disabled');
}
},
success: function(data) {
},
error: function(data) {
//
}
});
};
you'd be updating code in your mysite/backend folder to have some incoming route to insert data into django db using some serializer
sorry I don't have more specific details, but just wanted to convey the general idea
Here's some more information on Django serializers: http://www.django-rest-framework.org/api-guide/serializers/
another tutorial on adding an additional route to django could help

Kendo Grid Pass Form Data as Parameter Angular to MVC

I am switching from the Angular UI-Grid to the Kendo UI-Grid in my application. Currently, search criteria is collected via a search form then sent to my MVC Controller method via a Service (like below):
generalsearchService.submitSearch($scope.form)
.success(function (data) {
$scope.gridOptions.data = (data);
});
However, I cannot figure out how to pass the form data to the method using the Kendo grid. I have tried the following:
var form = $scope.form;
$scope.mainGridOptions = {
dataSource: new kendo.data.DataSource({
type: "aspnetmvc-ajax",
transport: {
read: "/SSQV4/SSQV5/Search/SubmitCriteria",
type: "POST",
data:{form: form}
},
schema: {
data: "Data",
total: "Total"
},
pageSize: 25,
serverPaging: true,
serverFiltering: true,
serverSorting: true
}),
My MVC Controller method (first line):
public async Task<ActionResult> SubmitCriteria(ContractorSearchViewModel form)
Update: I was able to pass the parameter to the controller by changing the read url to a function like below:
read: function() {
generalsearchService.submitSearch(form)
.success(function (data) {
return data;
});
}
However, even though the method executes correctly, the grid does not update with the new data.
Any assistance is greatly appreciated!
Although the service call above was hitting the MVC controller, the data was not populating the grid. The service call needed to be tweaked a little. Here is what finally worked:
dataSource: new kendo.data.DataSource({
transport: {
read: function (e) {
generalsearchService.submitSearch(e.data, form)
.then(function success(response) {
e.success(response.data);
});
}
},
schema: {
data: "Data",
total: "Total"
},
pageSize: 25,
serverPaging: true,
serverFiltering: true,
serverSorting: true
}),
"e.data" actually sends the Page, PageSize, Filters and Sort information while "form" is the collected form data which serves as parameters for the stored procedure. I also had to remove "[DataSourceRequest]" for the DataSourceRequest to actually send all information using my service. The http call in the service looks like this:
this.submitSearch = function (command, form) {
return $http.post('/SSQV4/SSQV5/Search/SubmitCriteria', {'command': command, 'form': form});
};
and the MVC controller method looks like this:
public async Task<ActionResult> SubmitCriteria(DataSourceRequest command, ContractorSearchViewModel form)
I hope this helps someone else. Happy coding!

ASP.Net MVC with Angular and Kendo UI

I'm new to ASP, Kendo and programming in general.
I’m trying to use Kendo Grid to CRUD the database; but I am kind of lost.
I have a simple class: Person, with Name and Surname.
The generated Controller and View works just fine, I can CRUD the database.
Then, using Angular I created this module:
`angular.module("KendoDemos2", ["kendo.directives"])
.controller("MyCtrl2", function ($scope) {
$scope.mainGridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: { url: "/Person/Read", dataType: "json" },
create: { url: "/Person/Create", dataType: "json", type: "POST" },
update: { url: "/Person/Update", dataType: "json", type: "PUT" },
destroy: { url: "/Person/Delete", dataType: "json", type: "DELETE" },
parameterMap: function (options, operation) {
if (operation !== "read") {
console.log(options)
return kendo.stringify(options);
}
}
},
batch: false,
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Name: { type: "string },
Surname: { type: "string" } }
}
}
})`
The problem is:
First, When I create a new person on the Grid, when I press “Create”, I don’t know if the data is being passed to the controller.
Second, in the controller, I have no idea of how to receive this information (a json, I believe).
Sorry, I am a total beginner.
EDIT
I have this method on the Controller:
[HttpPost]
public ActionResult Create(Person model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has Occurred");
}
}
So, this is being sent to the Person/Create method:
{ Name: "John", Surname: "Doe"}
Which return Success;
But how do I get these properties from the Json, and populate the model?
Ok so.
POST = create
GET = well Get in the context of the type of request from
browser to server
PUT = Update
DELETE = exactly Delete
so those are the verbs associated with HTTP in which RESTFUL APIS reside, for the most part there are lot more to look at, behind the scope of this answer.
as a result of the nature of the call it already understands that certain things like the type of data that you sent was in Content-Type: application/json.
The one thing missing from that method which I am surprised it wasn't there was
[FromBody], unless you hand coded the Method yourself rather than scaffolded it. Understandable for someone starting out. :)
to see this placing one of those break points next to the if statement will allow you to see if model was indeed populated with the contents of the post call.
[HttpPost] //because we want to create (new Person(){}) right?
public ActionResult Create([FromBody] Person model){
if(model != null && model.IsValid){
//EntityFramework or what ever DB you are using
_context.Person.Add(model);
_context.SaveChanges();
//doing this returns to the client that it was created as well as the
//Id of the newly inserted record. model.Id was automagically updated with the Id.
return Created("api/person/create", model);
}
else{
//something was horribly wrong with the model sent
return BadRequest("Invalid Model");
}
}
I think that will cover the broad strokes of the question. I think you are using an older version of asp.net so JsonResult might be available as well, BadRequest and Created assume ApiController is being used or Controller in Asp.net Core
mvermef, thank you very much for all the explanation.
I’m using ASP.Net MVC 5, with EF.
I did as you told and it work perfectly.
I haven’t included Web API at first, but needed it to make the [FromBody] work.
Another small but important thing was include contentType on the kendo configuration:
create: { url: "/Person/Create", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8" },

Kendo ComboBox not populating on REST GET

Trying to display "COLUMN_NAME" text in combobox. Here is the successful '200' response with parsed string from the browser:
[{"COLUMN_NAME":"Account","DATA_TYPE":"char"},"COLUMN_NAME":"Address","DATA_TYPE":"char"},...}]
Here is my js:
var dataSourceCustomers = new kendo.data.DataSource({
transport: {
read: {
url: "http://127.0.0.2:6080/arcgis/rest/services/Wks/WW/MapServer/exts/RestSOE/Search%20Parameters?searchType=CUSTOMER&f=",
dataType: "jsonp",
type: 'GET'
}
},
schema: {
data: ["COLUMN_NAME","DATA_TYPE"],
}
});
dataSourceCustomers.read();
The combobox however is blank. Thanks in advance!
The problem is the definition of schema.data that you define it as an array and this is not supported. In addition and according with you example of JSON you don't need it.
And in the ComboBox you define where on each item of the array is where you have the field for the Combo.
It should be like:
var dataSourceCustomers = new kendo.data.DataSource({
transport: {
read: {
url: "http://127.0.0.2:6080/arcgis/rest/services/Wks/WW/MapServer/exts/RestSOE/Search%20Parameters?searchType=CUSTOMER&f=",
dataType: "jsonp",
type : 'GET'
}
}
});
$("#combo").kendoComboBox({
dataSource : dataSourceCustomers,
dataTextField: "COLUMN_NAME"
})
BTW: Your example looks like JSON and not JSONP. Is it JSONP?

Resources