Kendo DataSource with sending dynamic data to the server - c#

I'm new to Kendo and from several days I'm trying to figure out how to populate kendo grid with search data. My case is the following:
I have javascript viewmodel:
sl.kendo = function () {
var billingReportViewModel = kendo.observable({
billingReportCriteria: [],
executeSearch: function (e) {
var $grid = $("#gridResults").data("kendoGrid");
$grid.dataSource.read();
$grid.refresh();
}
});
return {
billingReportViewModel: billingReportViewModel
}
} ();
And I initialize the billingReportCriteria from the server with this function:
var initCriteriaViewModel = function () {
$.ajax({
url: 'GetBillingReportCriteria',
type: "GET",
dataType: "json",
success: function (model) {
**$.extend(sl.kendo.billingReportViewModel.get("billingReportCriteria"), kendo.observable(model));**
// bind to the viewModel
kendo.bind($("#searchTable"), sl.kendo.billingReportViewModel);
}
});
}()
Than I declare my grid DataSource that sends this billingReportCriteria to the server as parameter:
var gridDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "GetBillingReportResults",
data: JSON.stringify(sl.kendo.billingReportViewModel.get("billingReportCriteria")),
cache: false,
type: "POST"
}
},
schema: {
data: "Items",
total: 10 // total number of data items is returned in the "count" field of the response
}
});
And I init my kendo grid:
$("#gridResults").kendoGrid({
columns: [
{
field: "Name"
},
{
field: "Title"
}],
dataSource: gridDataSource,
autoBind: false
});
When I execute the search from the view model 'executeSearch' I go the server, but the billingReportCriteria is empty! When I check the 'billingReportViewModel' value from F12 Chrome tools everything seems to be OK, but when I check the value of 'sl.kendo.billingReportViewModel.billingReportCriteria' or 'sl.kendo.billingReportViewModel.get("billingReportCriteria")' - it's empty though 'sl.kendo.billingReportViewModel.get("billingReportCriteria.Name")' for example has the right value!
Can you suggest what the problem is? Somehow I can't send the right 'billingReportCriteria' to the server!

I figure out the following thing. When I get the method on the server that is responsible for returning the results the only way I can get the passed parameters is by using the Response.Form or Response.QueryString in the body of the method. How can I pass the arguments to that method so I can get them like this:
public JsonResult GetBillingReportResults(string billingCriteria)
{
string criteria = Request.Form["billingCriteria"]; //I can do it like this, but I want to pass the arguments as method parameters
}

Related

How to get values inside object got through Json

I am using .NET MVC4
I have used javascript function as below:
function ShowDomainComponentDetail(compCode) {
alert(compCode);
$.ajax({
url: "/PP/getDomainComponentDetailWithDomain",
data: {
'ComponentCode': compCode
},
dataType: "json",
type: 'POST',
cache: false,
success: function (_responseData) {
$('#divShowDomainCompDetail').show();
alert(_responseData.Data)
},
error: function () {
//
}
});
}
Upon success I am getting list in .net as:
IdObservation=1, ObservationName="Started" , ObsType="Announced";
IdObservation=2, ObservationName="Not Started" , ObsType="Un Announced";
IdObservation=3, ObservationName="Declared" , ObsType="Announced";
My problem is i am not abl;e to access this list inside Ajax sucess block.
How can i access this list as:
alert(_responseData.IdObservation);
alert(_responseData.ObservationName);
(Further i am going to assign this to labels).
Please help me.
EDIT 1 :
My Serverside Function returning list:
public JsonResult getDomainComponentDetailWithDomain(string ComponentCode)
{
try
{
List<TEAMS_PP.Entity.correlations> compDetail_list = new correlation().getDomainComponentDetailswithDomain(ComponentCode);
return Json(compDetail_list);
}
catch (Exception)
{
List<TEAMS_PP.Entity.correlations> BlankList = new List<TEAMS_PP.Entity.correlations>();
return Json(BlankList);
}
}
Use index with data object like below:
alert(_responseData[0].IdObservation);
loop through object and get values for each object.
you can use the $each to iterate it
$.each(_responseData, function (key, value) {
var arr = value.IdObservation;
});

KendoUI Cascading Dropdowns -- Retrieving json data from dropdown to use in controller

Oh boy what did I get myself into this time. Have to get some KendoUI cascading dropdrown lists working properly but I figure I will start off with two for now. Basically I need to retrieve whatever the user chooses for the first list in the view and send that back to the controller then pass it to an Entity Framework method (which I already have setup). Here is what I have now. The controller then passes back the appropriate 2nd dropdown list based on the first dropdown division value selected. I have tried using the Kendo stringify(data) trick in the parametermap as well as using cascadeFrom: "division", as suggested in the kendoui docs but that hasnt worked so far. Thus leading me to this interesting creation so far.
Any help or Garfield Comics are greatly appreciated.
The JS for the dropdownlists;
var divisions = $("#division").kendoDropDownList({
optionLabel: "Select category...",
dataTextField: "CodeAndDescription",
dataValueField: "Code",
dataSource: {
// type: "odata",
serverFiltering: true,
transport: {
read: {
url: VIPApiUrl + "GetDivision",
dataType: "json",
async: false,
type: "POST",
}, parameterMap: function (options, type) {
// edit VARS passed to service here!
if (type === 'read') {
return {
'division': options.division,
// 'criteria[0].Value': options.value
// ...
};
}
}
}
},
change: function () {
var value = this.value();
alert(value);
if (value) {
itemGroupDataSource.one("change", function () {
itemGroup.current(null);
}).filter({
field: "ID",
operator: "eq",
value: parseInt(value)
});
itemGroup.enable();
} else {
itemGroup.enable(false);
}
itemGroup.select(0);
}
}).data("kendoDropDownList");
var itemGroupDataSource = new kendo.data.DataSource({
//type: "odata",
serverFiltering: true,
transport: {
read: {
url: VIPApiUrl + "GetItemGroup",
dataType: "json",
async: false,
type: "POST",
}
}
});I
My controller where I need to access the json:
#region GetItemGroup
[HttpPost]
public List<ItemGroupsDTO> GetItemGroup(JObject jsonData)
{
dynamic json = jsonData;
string x = null; //intentionally pass null values
string division = json.division;
List<ItemGroupsDTO> ItemGroups = new List<ItemGroupsDTO>();
var ItemGroupEOList = new VIPItemGroupBOList();
ItemGroupEOList.Load(x, x, division, x, x, x, x, x, x, x, false);
foreach (var d in ItemGroupEOList)
{
var ItemGroup = new ItemGroupsDTO();
ItemGroup.Code = d.Code;
ItemGroups.Add(ItemGroup);
}
return ItemGroups;
}
#endregion
Okay I fixed this by changing the parameter map in the itemGroupDataSource to:
parameterMap: function (options, operation) {
return {
division: options.filter.filters[0].value
}
}
and changed the value field to:
dataValueField: "CodeAndDescription",
So I am guessing I partly wasn't giving the EO the right information but hopefully this helps someone in a Jam.

Pass data in a .getJSON. Possible? How?

I'm doing an app and I got a select where the user can choose different Teams. Each team contains a couple of patients. I save the chosen team with the data-bind selectedOptions and stores the option to an observable called 'selectedTeam'.
I'm receiving a list of patients by calling
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
self.searchPatients();
Back at my APIController I got a method that asks the DB for patients. This calls takes different arguments, one of them being what team to search from.
My question is how to pass the observable 'selectedTeam' to my APIController, convert it to a string to pass it to the DB call.
thx
You can pass the data as a second argument of getJSON function :
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", { param1: 'anyvalue' }, function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
self.searchPatients();
Assuming the server method looks like as follow :
[HttpGet]
public Object GetPatients(String team)
{
// return the patients
}
You should use this JavaScript :
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", { team: self.selectedTeam() }, function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
Because self.selectedTeam is an observable you can't send it to the server.What you want to send is its value. That's why you need to 'call' the observable.
self.selectedTeam() // returns the value of the observable.
I hope it helps.
To pass data to controller you can use jquery ajax call as follows,
$.ajax({
type: "POST",
url: "api/API/GetPatients",
data: JSON.stringify(yourObject), // data to be passed to controller
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// your success call
},
error: function () {
alert("Unable to Save.");
}
});

Type error: url is undefined extjs 4 populating combobox

I am creating a combo box using extjs 4 in an editable grid (im using extjs 4) and i am using external ajax call to populate it rather than using a extjs proxy, the reason is that i am using the same call for loading other combo boxes. So i thought why not use the same function. Here is the code for store, model, dropdown and ajax call:
var drpdwnitems = "";
Ext.define('rStatusRecord', {
extend: 'Ext.data.Model',
fields: [
{ name: 'code', type: 'string' },
{ name: 'value', type: 'string' }
]
});
var dsStatus = Ext.create('Ext.data.Store', { model: 'rStatusRecord', data: [] });
var timeSelectField_1 = {
xtype: 'combobox',
typeAhead: true,
displayField: 'code',
valueField: 'value',
store: dsStatus,
triggerAction: 'all'
};
This field is basically used in grid panel's column for the editing purpose. AJax call is basically returning a string.
$.ajax({
type: "GET",
url: "XHR/Task_TypesCalls.aspx?TL_A=1",
error: function() { alert('Error loading document'); },
success: loadAvailableTasksList
});
function loadAvailableTasksList(contents, status) {
drpdwnitems = contents.split("!");
if (status != "success") return;
var drpdwnitemsind;
dsStatus.removeAll();
for (i = 0; i < drpdwnitems.length; i++) {
drpdwnitemsind = drpdwnitems[i].split(":");
statusRecord = Ext.create('rStatusRecord', {
code: drpdwnitemsind[0], //"",
value: drpdwnitemsind[0]//""
});
dsStatus.add(statusRecord);
} //end of loop
}
Now when i edit the field and open the combo box, there is an error TypeError: url is undefined
This error is in the file ext-all-debug.jsWhat my guess is that url config of store is necessary and im not providing it. OR am i doing something wrong here?
See: http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.field.ComboBox-cfg-queryMode
You want to set it to local.

display json data from controller inside view

Inside my controller there is JsonResult action which returns me a list of House object.
I want onclick using ajax to retrieve these data and to display json data inside my view.
Inside firebug I'm able to see proper Response and Json result but I dont know how to display inside my view.
function GetTabData(xdata) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: xdata }),
success: function (result) {
// tried with these but it doesnt work
// result = jQuery.parseJSON(result);
// alert(result.Title);
},
error: function () { alert("error"); }
});
}
public JsonResult GetTabData()
{
...
var temp = getMyData...
return Json(temp, JsonRequestBehavior.AllowGet);
}
// View page
<div id="showContent">
// Json data should appear here
</div>
Inside firebug JSON tab when success:function(result) is empty
I have following data:
Id 149
PropertyType "Apartment"
StreetNumber "202B"
CityName "Sidney"
Title "My test data"
success: function (json) {
var data = null;
$.each(json.items,function(item,i){
data = '<div>'+item.Id+ ' ' + item.CityName +'</div>';
$("#showContent").append(data);
});
}
First of all, you can specify the dataType attribute in your ajax call to 'json' and then don't have to decode the json response again -
dataType: 'json'
Then, you don't need to use parseJSON. Simply use result.Title etc.
success: function (result) {
alert(result.Title);
var showContent = $('#showContent');
showContent.html(result.Id+','+result.Title);
},
EDIT: As Mukesh said, you can have the ajax function return json without using any extra decoding.
The ajax call result is already an object. You can do whatever you want with it it inside the success function.
For example you could create a table of the information dynamically inside the function, or send the data to another function by calling the function inside that success function. Once you leave the success function, the data is not usable anymore.
Access the data object like any object (data.someProperty).

Categories