Iteration of resultset in schema method of kendo mvc grid - kendo-ui

I'm using kendo MVC grid with custom binding of datasource. I want to do some preprocess to resultset data in client side javascript before binding the data to grid. But I dont know how to do the iteration of resultset in schema method of kendo custom binding. Anyone please tell me how to iterate the data in schema method.
My Code:
.DataSource(dataSource => dataSource
.Custom()
.Type("aspnetmvc-ajax")
.Transport(transport => transport
.Read(new
{
url = Url.Action("Action", "Controller"),
beforeSend = new Kendo.Mvc.ClientHandlerDescriptor
{
HandlerName = "beforeSend"
}
})
)
.Schema(schema => schema
.Data("Data")
.Total("Total")
.Errors("Errors")
)
)
Thanks.

You can use the Schema's "parse" function to parse the server response: http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-schema.parse
I can't speak directly to how to do this using the MVC approach, but in pure javascript you could do this to convert a property called StartDate to a Date object (for example)
var mydataSource = new kendo.data.DataSource({
transport: {
read: function(e) {
var data = GetData(); //do something to get data
e.success(data);
}
},
schema: {
parse: function (response) {
$.each(response, function (i, item) {
if (item.StartDate && typeof item.StartDate === "string") {
item.StartDate = kendo.parseDate(item.StartDate);
}
});
return response;
}
}
}
});

Related

Form data is empty after using append?

I have a problem to append anything in form data. Its always empty. How can I append image file and some other data?
var data = new FormData();
fileResult = this.$els.fileIntroImage.files;
data.append('name',this.property_credentials.name);
data.append('default_image',this.$els.fileIntroImage.files[0],File);
console.log('data',data);
Took me a while to get my head around file uploads with Vue.
Here is the methods object on my Vue component:
methods: {
upload(e) {
e.preventDefault();
var self = this;
var formData = this.gatherFormData();
this.$http.post('/path/to/upload/method', formData)
.then(response => {
//do stuff
},
(response) => {
//show error
});
},
gatherFormData() {
const data = new FormData();
data.append('image', this.$refs.image.files[0]);
data.append('other_field', this.other_field);
return data;
}
},
This should then function as as a normal file field as far as Laravel is concerned.
It can be logged, you just need to log each item. You can use FormData’s iterator function to do so.
var data = new FormData();
data.append('name',this.property_credentials.name);
data.append('default_image',this.$els.fileIntroImage.files[0],File);
data.forEach(el => console.log(el));

kendo ui datasource read method makes two requests

I have a grid with a datasource read method
this.editorGridConfig = {
dataSource: {
transport: {
read: options => {
this.getSummaryData().then(res => {
options.success(res.data);
});
}
}
getSummaryData() {
console.log('get summary data');
let url = 'myEndPoint';
return ajaxRequest(url);
}
The getSummaryData is been called successfully and returns an array of objects.
The problem is when the options.success(res.data) is called kendo makes a new request on the this.getSummaryData is called twice.
if you are using a kendo route then this is the issue.
router.navigate('/page/' + e.index);
fires read() inside pagination onChange() and dataSource.query()
Solution is :
var url = window.location.href;
var pagelessUrl = url.indexOf("/page/") === -1 ? url.length - 1 : url.indexOf("/page/");
window.history.pushState('page'+e.index, document.title, url.substring(0,pagelessUrl)+"/page/" + e.index);

Update knockout viewmodel when uploading documents via ajax

I'm trying to use knockout for a view where I'm uploading documents and showing a list. For this I'm using jquery.form.js in order to upload them using ajax. I've changed that to use knockout and my viewmodel looks like this
var ViewModel = function (groups) {
var self = this;
self.groups = ko.observableArray(ko.utils.arrayMap(groups, function (group) {
return {
planName: ko.observable(group.Key),
documentList: ko.observableArray(ko.utils.arrayMap(group.Values, function (value) {
return {
document: ko.observable(new Document(value))
};
}))
};
}));
var options = {
dataType: 'json',
success: submissionSuccess
};
self.add = function () {
$('#addForm').ajaxSubmit(options);
return false;
};
function submissionSuccess(result) {
alert('success');
}
};
Having one Document function for doing the mapping. I'm stuck when receiving the Json data from the controller. The result is correct, a list of objects in the same format I'm receiving on first load but I don't know how to "refresh" the viewmodel to use this new list.
Don't know if using the ko mapping plugin would make it easier as I have never used it and don't even know if it's applicable for this.
The controller method, in case is relevant, is this (if something else neede let me know althoug won't have access to the code in the next hours)
[HttpPost]
public ActionResult AddDocument(AddDocumentViewModel viewModel)
{
var partyId = Utils.GetSessionPartyId();
if (viewModel.File.ContentLength > Utils.GetKBMaxFileSize * 1024)
ModelState.AddModelError("File", String.Format("The file exceeds the limit of {0} KB", Utils.GetKBMaxFileSize));
if (ModelState.IsValid)
{
_documentsManager.AddDocument(viewModel, partyId);
if (Request.IsAjaxRequest())
{
var vm = _displayBuilder.Build(partyId);
return Json(vm.Documents);
}
return RedirectToAction("Index");
}
var newViewModel = _createBuilder.Rebuild(viewModel, partyId);
return PartialView("_AddDocument", newViewModel);
}
Thanks
EDIT: I came up with this code which seems to work (this function is inside the ViewModel one
function submissionSuccess(result) {
self.groups(ko.utils.arrayMap(result, function (group) {
return {
planName: ko.observable(group.Key),
documentList: ko.utils.arrayMap(group.Values, function (value) {
return {
document: new Document(value)
};
})
};
}));
};
Are you sure the documentList and document need to be observables themselves ?
To update the list you can push to it as you'd do on a regular array.
You could try something like this:
function submissionSuccess(result) {
self.groups.removeAll();
$.each(result, function(index, value) {
var documentList = [];
$.each(value.Values, function(index, value) {
documentList.push(new Document(value));
});
var group = {
planName:value.Key,
documentList: documentList
};
self.groups.push(group);
});
};

Ember: Fetching data for objects that depend on each other

I'm trying to build a front-end for a metrics tool with Ember. The code that I've written so far has been very much influenced by Eviltrout's emberreddit application
https://github.com/eviltrout/emberreddit
The goal is to have two classes that depend on each other: metrics and filters.
1) Once the application initializes, the filters, which are instances of the Filter-class, are loaded from the server. Once the filters have loaded, they are displayed as checkboxes on the screen. After that, the metrics objects should take the filters as parameters and query the server for data.
2) Once the user changes the checkboxes and thus updates the filter objects, the application should take the filters as parameters again and fetch new metrics data from the server.
My problem is that I don't know how to handle the dependencies between these two sets of objects with asynchronous ajax calls. At it's current state, my application doesn't finish loading the filters when it already starts loading the metrics. Therefore, the filters don't get passed as parameters for the metrics ajax-call.
My question is: What's the best way to do this ember? There surely has to be a way to handle the order of ajax calls. My intuition is that manually adding observers isn't the way to go.
Here are the models of my application:
//FILTER MODELS
var defaultFilters = ['dates', 'devices'];
//set Filter class. The Filter object will be multiplied for each filter.
App.Filter = Ember.Object.extend({
//capitalize first letter to get title
filterTitle: function() {
return this.get('id').charAt(0).toUpperCase() + this.get('id').slice(1);
}.property('id'),
//set attribute to see if filter has loaded
loadedFilter: false,
//create method to load filter values from server
loadValues: function() {
var filter = this;
return Ember.Deferred.promise(function (p) {
if (filter.get('loadedFilter')) {
p.resolve(filter.get('values'));
} else {
p.resolve($.getJSON("http://127.0.0.1:13373/options/" + filter.get('id')).then(function(response) {
var values = Ember.A();
response[filter.get('id')].forEach(function(value) {
values.push(value);
});
filter.setProperties({values: values, loadedFilter: true});
return values;
}))
}})}
}
);
//reopen class to create "all" method which returns all instances of Filter class
App.Filter.reopenClass({
all: function() {
if (this._all) {return this._all; }
var all = Ember.A();
defaultFilters.forEach(function(id) {
all.pushObject(App.Filter.create({id: id}));
});
this._all = all;
return all;
}});
//Create a Filters array to store all the filters.
App.Filters = App.Filter.all();
//METRIC MODELS
App.Metric = Ember.Object.extend({
metricTitle: function() {
return this.get('id').charAt(0).toUpperCase() + this.get('id').slice(1);
}.property('id'),
loadedMetric: false,
filtersBinding: 'App.Filters',
loadValues: function() {
var metric = this;
var filters = metric.get('filters');
if (filters.get('loadedFilters'))
console.log('loading metrics');
return Ember.Deferred.promise(function (p) {
if (metric.get('loadedMetric')) {
p.resolve(metric.get('values'));
} else {
p.resolve(
console.log('sending ajax'),
$.ajax({
url: "http://127.0.0.1:13373/" + metric.get('id') + "/",
data: JSON.stringify(metric.get('filters')),
}).then(function(response) {
var values = Ember.A();
response[metric.get('id')].forEach(function(value) {
values.push(value);
});
metric.setProperties({"values": values, "loadedMetric": true});
return values;
}))
}})}
});
App.Metric.reopenClass({
findByView: function(searchView) {
if (this._metrics) {return this._metrics; }
var metrics = Ember.A();
defaultMetricsSettings.forEach(function(metric) {
if (metric.view == searchView)
metrics.pushObject(App.Metric.create({id: metric.id},{view: metric.view}, {calculation: metric.calculation}, {format: metric.format}, {width: metric.width}));
});
this._metrics = metrics;
return metrics;
}
});
And here are the routes:
App.ApplicationRoute = Ember.Route.extend({
//set application routes model to all filters
model: function() {
return App.Filter.all();
},
//after filter has loaded, let's load its values
afterModel: function(model) {
return model.forEach(function(item) {
item.loadValues();
});
},
//create a controller called ApplicationController and pass the filter as its model
setupController: function(controller, filter) {
controller.set('model', filter);
}
});
App.DashboardRoute = Ember.Route.extend({
model: function() {
return App.Metric.findByView('Dashboard');
},
afterModel: function(model) {
return model.forEach(function(item) {
item.loadValues();
});
},
setupController: function(controller, metric) {
controller.set('model', metric);
}
});
Controllers:
App.ApplicationController = Ember.ArrayController.extend({
//ApplicationController controls all the filters. Let's create a controller to handle each instance of a filter
itemController: 'filter'
});
App.FilterController = Ember.ObjectController.extend({
//this sets the titleId property that is used only for binding html attributes in template. Stupid way to do this.
titleId: function() {
return "#" + this.get('filterTitle');}.property('filterTitle')
});
Your afterModel hook could do this in a sequence of dependent promises. The current implementation is returning immediately, instead you chain the promise and finally return the last promise as the result of the hook. The router will wait for the whole set of calls to complete before continuing to setupController.
afterModel: function(model) {
var promise;
model.forEach(function(item)) {
if (promise) {
promise = promise.then(function() {
item.loadValues();
});
} else {
promise = item.loadValues();
}
}
return promise;
}
I'm not sure how many of the calls you have, but you may want to batch some of these together to reduce the number of HTTP requests.

Uploading files to tastypie with Backbone?

Checked some other questions and I think my tastypie resource should look something like this:
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
class ImageResource(MultipartResource, ModelResource):
image = fields.FileField(attribute="image")
Please tell me if that's wrong.
What I don't get, assuming the above is correct, is what to pass to the resource. Here is a file input:
<input id="file" type="file" />
If I have a backbone model img what do I set image to?
img.set("image", $("#file").val()); // tastypie doesn't store file, it stores a string
img.set("image", $("#file").files[0]); // get "{"error_message": "'dict' object has no attribute '_committed'" ...
What do I set my backbone "image" attribute to so that I can upload a file to tastypie via ajax?
You may override sync method to serialize with FormData api to be able to submit files as model's attributes.
Please note that it will work only in modern browsers. It worked with Backbone 0.9.2, I advise to check the default Backbone.sync and adopt the idea accordingly.
function getValue (object, prop, args) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ?
object[prop].apply(object, args) :
object[prop];
}
var MultipartModel = Backbone.Model.extend({
sync: function (method, model, options) {
var data
, methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
}
, params = {
type: methodMap[method],
dataType: 'json',
url: getValue(model, 'url') || this.urlError()
};
if (method == 'create' || method == 'update') {
if (!!window.FormData) {
data = new FormData();
$.each(model.toJSON(), function (name, value) {
if ($.isArray(value)) {
if (value.length > 0) {
$.each(value, function(index, item_value) {
data.append(name, item_value);
})
}
} else {
data.append(name, value)
}
});
params.contentType = false;
params.processData = false;
} else {
data = model.toJSON();
params.contentType = "application/x-www-form-urlencoded";
params.processData = true;
}
params.data = data;
}
return $.ajax(_.extend(params, options));
},
urlError: function() {
throw new Error('A "url" property or function must be specified');
}
});
This is excerpt from upload view, I use <input type="file" name="file" multiple> for file uploads so user can select many files. I then listen to the change event and use collection.create to upload each file.
var MultipartCollection = Backbone.Collection.extend({model: MultipartModel});
var UploadView = Backbone.View.extend({
events: {
"change input[name=file]": "changeEvent"
},
changeEvent: function (e) {
this.uploadFiles(e.target.files);
// Empty file input value:
e.target.outerHTML = e.target.outerHTML;
},
uploadFiles: function (files) {
_.each(files, this.uploadFile, this);
return this;
},
uploadFile: function (file) {
this.collection.create({file: file});
return this;
}
})

Resources