I'm making an addition to a working Kendo UI grid to allow it to update based on an id passed in from a textbox. I'm calling my controller from the ajax, and everything works as expected until I try and create the kendo.data.DataSource() for my grid inside of the ajax success. The result looks as expected but anything I do to assign it to the data source does not seem to work. The data shows nothing and the grid comes up empty.
The model expected by the grid does match the one in my controller. I've looked at other questions and the kendo ui docs but I can't seem to figure out what I'm doing wrong... any help will be appreciated.
Ajax:
$.ajax({
type: "POST",
url: '#Url.Action("Search")',
data: JSON.stringify({ id: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
var grid = $("#Grid").data("kendoGrid");
var data = new kendo.data.DataSource(result);
grid.dataSource.data(data);
grid.refresh();
}
});
Controller:
public ActionResult Search([DataSourceRequest]DataSourceRequest request, string id)
{
IEnumerable<SearchModel> data = GetData(id);
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
You are using the ToDataSourceResult() extension method on the server so you need to using the Data property of result to assign to the data property of the DataSource object you are creating on the client. Also, you should use the setDataSource method of the grid not grid.dataSource.data(). Lastly, you want to call the read() method of the dataSource grid property, not grid.Refresh().
$.ajax({
type: "POST",
url: '#Url.Action("Search")',
data: JSON.stringify({ id: id }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
var grid = $("#Grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
data: result.Data
});
grid.setDataSource(dataSource);
grid.dataSource.read();
}
});
You are creating the DataSource incorrectly. Assuming the result of your AJAX call returns an array, you must then wrap it in an object with a data property that holds the array of data.
$.ajax({
// ...
success: function (result) {
var grid = $("#Grid").getKendoGrid();
var data = new kendo.data.DataSource({ data: result });
grid.dataSource.data(data);
grid.refresh();
}
});
The following is an alternative way to create a DataSource and allows passing in an array (unwrapped), a DataSource configuration object, or even a preexisting DataSource object.
var data = kendo.data.DataSource.create(obj);
This approach is preferable b/c it is more flexible.
I hope that helps!
Related
How to load kendo grid data with ajax call using dataSource.data method. I have tried following but it is not working. $('#AAMaintenance').data('kendoGrid').dataSource.data(result);
function filterOnSubmit() {
var data = {};
data["ExaminerNo"] = $("#txtExaminerNo").val();
data["ExaminerName"] = $("#txtExaminerName").val();
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetFilteredAAMaintenanceDetails", "AAMaintenance")',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify({ aaMaintenanceFilter: data }),
success: function (result) {
$('#AAMaintenance').data('kendoGrid').dataSource.data(result);
$('#AAMaintenance').data('kendoGrid').refresh();
}
});
}
Assuming that the dataSource hasn't been setup for the Kendo grid control prior to the ajax call to retrieve the data, you should instantiate this before setting it as the datasource:
var ds = new kendo.data.DataSource({
data: result
});
$("#AAMaintenance").data("kendoGrid").setDataSource(ds);
A few notes aside from this, and based on Telerik documentation:
If the result returned from the server is a complex object (unknown currently), you may need to look into schema.model.
Ensure that the column declaration field attributes match the names assigned to the object attributes you wish to display, for example note in this example how the field: "name" column matches the name attribute being added to the dataSource.
I want to pass the Htmlhelper helper value of a dropdown in an ajax call
#Html.DropDownListFor(m => m.LanguageRouteName, (SelectList)ViewBag.LanguageEnum, new { #onchange = "submitform(event)", #class = "input-medium", #id = "languageEnum" })
i am trying to pass the event but i need all the values of HtmlHelper 'helper'. How do i get this value? Please Help
$('#languageEnum').Onchange(function(){
var ddl val=$('#languageEnum').val();
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: "ddldata:ddl", // dropdown data
dataType: "json", //Expected data format from server
success: function (json) {//On Successful service call
var result = json.name;
$("#dvAjax").html(result);
}
})
});
I have a Kendo UI DataSource that works when I use fetch(), but when I use the exact same configurtation with read() it fails. This is a problem as I need to retrieve data more than once and I can't do that with fetch().
Here is the DataSource code -
var FieldsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "../WebServiceAddress",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false
},
parameterMap: function() {
return "{some mapping that has been confirmed to work}";
},
schema: {
data: function (data) {
if (data && data.d) {
//execution gets to here and stops
return data.d;
}
else {
return [];
}
},
}
});
Here is the code that calls the DataSource.read() function -
function loadFields() {
FieldsDataSource.read(function() {
var data = this.data();
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var dataitem = data[i].Key;
$("#" + dataitem + "_field").prop("checked", data[i].Value);
}
}
});
}
If I change FieldsDataSource.read(function() to FieldsDataSource.fetch(function() everything works, but that doesn't make sense as I was under the improession that read and fetch do the same thing the difference being fetch only gets data once.
What I do know is that the data is being returned from the server, I can see it in fiddler - but the execution stops in the schema section where I flagged it in my code sample.
Apologies if I am asking a really obvious question, but I'm very new to Kendo.
have a look at the kendo demo site, this post explains how to read remote data quite nicely. I beleive the schema.data requires only string value. Configure your model and parse and then just call read(), your datasource.data collection will get populated and then you can play with it.
Also note that datasource.read() is async, thefore you populatefields method should be called from complete event of the datasource, not other way around. eg you might have no data in when populating.
transport: {
read: {
url: "../WebServiceAddress",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
complete : function () { }
},
I am new with knockout and mvc, so I need some help, my question is
my dropdown list is populating successfully from server, and on clicking save button calls Save method in controller. But problem is that in controller I am unable to receive json data i.e it is null. here is my code in view
var initialData = #Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = function(){
var self = this;
self.HomeAgencies = ko.observableArray(initialData.HomeAgencies);
self.selectedOrgUnit = ko.observable();
self.Save = function () {
$.ajax({
url: "#Url.Action("Save")",
type: "POST",
data: ko.toJSON(this),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(result) {alert(result.message)}
});
}
}
var vm = new viewModel();
ko.applyBindings(vm);
Where in controller i have following code
public JsonResult Save(string someData)
{
var message = string.Format("Saved {0} ", "successfully");
return Json(new { message });
}
string someData is always null, where I am expecting some json data.
Try to replace this to self in data and introduce field name and remove contentType.
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: { someData: ko.toJSON(self) },
dataType: 'json',
success: function (result) { alert(result.message); }
});
In your case context of the method can be changed from your object to html element that invoked them method or to window.
issue resolved. Problem was at controller side, in Action of controller pass the same model class instead parsing json manually.
I want to pass an array of strings from my view model (in form of an ko.observableArray) to the controller in Asp.net MVC.
As the ko.observableArray is an object rather than array, it cannot simply be passed through the $.ajax method and used as array in controller side.
How can I pass the data in ko.observableArray to controller so that I can use it as array on the controller side?
Knockout has two utility function called ko.toJS and ko.toJSON.
var myPlainObject = ko.toJS(root) will traverse your object and turn any observable into a plain JavaScript property.
var myJSONstring = ko.toJSON(root) will do the same and then do a JSON.stringify on the result.
So, you can use those functions on your viewModel to get plain JavaScript objects.
Info from the docs here.
If the items in your observableArray do not contain observables, then you could simply just retrieve the underlying array by doing myObservableArray()
Update: based on comment. This works fine for me:
var viewModel = {
items: ko.observableArray(["one", "two", "three", "four"]),
sendItems: function() {
$.ajax({
type: "POST",
url: "#Url.Action("Test")",
data: ko.toJSON(viewModel.items),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data) {
alert(ko.toJSON(data));
}
}
});
}
};
Against an action like:
//just echo back data
public JsonResult Test(List<String> myList)
{
return Json(myList);
}
Does this match what you are trying?