How to Pass Parameters to SignalR Read Opeartion of KendoUI DataSource - c#

I am using a Kendo UI dataSource to bind KendoUIScheduler through SignalR. How can I pass parameters to the read operation of the dataSource with SignalR bindings?
I am using the following code:
var hub = $.connection.schedulerHub;
var hubStart = $.connection.hub.start();
$('#scheduler').kendoScheduler({
mobile: true,
height: 600,
views: [
'day',
'week',
'month',
'agenda',
{ type: 'timeline', selected: true }
],
timezone: 'Etc/UTC',
dataSource: {
type: "signalr",
push: function (e) {
alert(e.type);
},
autoSync: true,
transport: {
signalr: {
promise: hubStart,
hub: hub,
server: {
read:"read",
update: "update",
destroy: "destroy",
create: "create"
},
client: {
read:"read",
update: "update",
destroy: "destroy",
create: "create"
}
}
},
schema: {
model: {
id: 'SchedulerID',
fields: {
SchedulerID: { type: 'number', from: 'SchedulerID' },
start: { type: 'date', from: 'Start' },
end: { type: 'date', from: 'End' },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
Title: { from: 'Title' },
isAllDay: { type: 'boolean', from: 'IsAllDay' },
recurrenceId: { from: "RecurrenceId" },
recurrenceException: { from: "RecurrenceException" },
recurrenceRule: { from: "RecurrenceRule" },
Users: { nullable: true, from: 'Users' },
},
}
}
},
group: {
resources: ['Users'],
orientation: 'vertical'
},
resources: [
{
field: 'Users',
name: 'Users',
dataSource: Users,
multiple: false,
title: 'Users'
}
]
});

I realize this question is old, but I was trying to find this same answer and didn't find any clear solutions. I did find some hints in other threads that led me to a solution although I'm sure there are better ones (I wasn't able to figure out how to send the parameters separately - only as one object).
In your datasource, use the parameterMap function to put in whatever custom parameters you want. When binding to WCF (commented code) you can separate the parameters for the call but I couldn't get that to work with the SignalR implementation.
type: "signalr",
transport: {
parameterMap: function (data, type) {
switch (type) {
case "read":
{
// this works
var request = {};
var chkunsub = $('#chkunsubscribed').is(':checked');
request.unsubscribed = chkunsub;
request.oKendo = data;
return request;
// Does not work (separating parameters)
//return {
// unsubscribed: chkunsub,
// oKendo: data
//};
}
// Does not work either (separating parameters)
//return kendo.stringify({
// unsubscribed: chkunsub ? 1 : 0,
// oKendo: data
//});
}
},
Note that the "data" variable contains the filter, paging, grouping, etc. (I'm binding to a grid but I would think it's the same for scheduler).
Then on the server side in your hub, you just need to mirror the class structure like this (my CKendoGridOptions class has all of the properties from the API such as page, skip, filter, etc).
Public Class EventRequestData
Public Property unsubscribed As Boolean
Public Property oKendo As CKendoGridOptions
End Class
' This works
Public Function read(data As EventRequestData) As OrmedReturnData
Dim oReturn As New OrmedReturnData
If IsLoggingEnabled() Then
WriteToEventLog("Hub getevent_item called")
End If
Dim oToken As TokenHelper.TokenData = TokenHelper.ValidateToken(New Guid(Context.Request.Cookies("token").Value))
If oToken.TokenOK = False Then
oReturn.Success = False
oReturn.ErrorMessage = ERROR_INVALID_TOKEN
Else
Dim oData As New EventItems
oReturn = oData.Getevent_items(data.unsubscribed, data.oKendo)
End If
Return oReturn
End Function
I hope this helps someone else who is trying to pass parameters to a read function using Kendo in jQuery and SignalR.

Related

Jtable only displays when stepping through debugger

Hi I am struggling to display my jtable. It only displays when I step through the javascript with the debugger.
$("body").on("click", "#tabRole", function () {
document.getElementById("1").className = "inactive";
document.getElementById("2").className = "active";
$('#Admin-details').load('../Admin/ADRoleAdmin');
jTableRoles();
});
This method loads ADRoleAdmin as a partial view into a div. Then jTableRoles() should load the jtable into a div (jTableRoles) inside ADRoleAdmin:
var jTableRoles = function () {
$(function () {
debugger;
$('#jTableRoles').jtable({
paging: true,
pageSize: 20,
sorting: true,
title: 'Roles',
onRowEdit: function (event, data) {
UpdateRoleDetails(data.records.RoleId, data.records.RoleName);
},
actions: {
listAction: '../Admin/GetRoles',
updateAction: 'dummy'
},
toolbar: {
items: [{
icon: '../Content/images/Misc/Add icon.png',
text: 'Create New',
click: function () {
UpdateRoleDetails(0, '');
}
}]
},
fields: {
Id: {
key: true,
list: false
},
Name: {
title: 'Role name',
},
Description: {
title: 'Role description',
sorting: false
}
}
});
$('#jTableRoles').jtable('load');
});
}
Please tell me what I am doing wrong or what I can do different to make it work.
Looping through the steps takes extra time.
It looks like the load of ADRoleAdmin is not finished on the moment the jTable is loaded.
Try to start the jtable after a certain timeout to check.
Preferably load the ADRoleAdmin an on it's postback load the jTable

Create chart with serverside object data using JSON

What I'm trying to do:
Create a chart and have it display data from the server (held in a C# object) every x mminutes. From googling using JSON (which I've never used before) would be best practice.
What I have so far:
I have the backend C# (using MVC 5) getting the correct data, lots of objects with lots of properties, some I want to display in the chart, others I don't.
I'v also started on a JSON function in my Index.cshtml which is where my graph is (currently set with static data, it's a simple jQuery plug-in).
The problem:
Unsure how to get specific object properties, to the JSON data and then to the chart data.
What would be the best way of achieving this?
Code:
Controller:
// GET: Graphs
public ActionResult Index()
{
return View();
}
public static List<server> GetServer()
{
Api api = new Api();
List<server> sList = api.GetServerStats();
return sList;
}
Script in INdex:
<script src="~/Scripts/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("someChart", {
title: {
text: "Space left on Server vs Total"
},
data: [
{
type: "column",
name: "Totals",
showInLegend: true,
dataPoints: [
{ label: "Space", y: 20 }
]
},
{
type: "column",
name: "Used",
showInLegend: true,
dataPoints: [
{ label: "Space", y: 10 }
]
}
],
axisY: {
prefix: "",
suffix: "GB"
}
});
chart.render();
}
$(document).ready(function () {
window.onload(function () {
$.ajax({
type: "POST",
url: "GraphController/GetServer",
data: { someParameter: "some value" },// array of values from object or just object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// need to push into jQuery function
}
});
});
});
</script>
Returning a serialised list of objects couldn't be easier with MVC, it takes a lot of the heavy lifting out of it for you if you just return a JsonResult:
public ActionResult GetServer() {
var api = new Api();
var = api.GetServerStats();
return Json(sList);
}
Debug the success of your ajax call to find out if result is what you want and expect, and then pass it to your chart script.
NOTE: From your use of wording (i.e. 'lots'), I'd recommend cutting down your list of server properties you return to your view. This is a perfect candidate for creating what's called a view model. This view model would be a kind of 'lite' version of your full server object. It would improve efficiency of serialisation for starters and, semantically, makes more sense.
I was doing same thing with highcharts and here is an approximate solution for you:
public ActionResult GetServer()
{
Dictionnary<server> sList = new Dictionnary<string,object>();
sList.Add("Totals",new{
type= "column",
name= "Totals",
showInLegend= true,
dataPoints= new List<dynamic>(){
new{ label= "Space", y= 20}/*,
new{ label= "label2", y= 30},*/
}
});
sList.Add("Totals",new{
type= "column",
name= "Used",
showInLegend= true,
dataPoints= new List<dynamic>(){
new{ label= "Space", y= 10}/*,
new{ label= "label2", y= 40},*/
}
});
return Json(sList, "text/json", JsonRequestBehavior.AllowGet);
}
Change window.onload=function(){} in
function drawChart(serverData){
var chart = new CanvasJS.Chart("someChart", {
title: {
text: "Space left on Server vs Total"
},
data: serverData,
axisY: {
prefix: "",
suffix: "GB"
}
});
chart.render();
}
$(document).ready(function () {
$.ajax({
type: "POST",
url: "GraphController/GetStuff",
data: { someParameter: "some value" },
// array of values from object or just object
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (serverData) {
// need to push into jQuery function
drawChart(serverData);
}
});
});

Web API 2.2 OData V4 - Kendo Grid - customize Created IHttpActionResult

I have a Kendo UI Grid wired up to odata CRUD services (Web API 2.2 OData V4). The dataSource configuration looks like the following - the baseUrl is the same for all, just the HTTP verb changes.
var dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
beforeSend: prepareRequest,
url: baseUrl,
type: "GET",
dataType: "json"
},
update: {
beforeSend: prepareRequest,
url: function (data) {
return baseUrl + "(" + data.CategoryId + ")";
},
type: "PUT",
dataType: "json"
},
create: {
beforeSend: prepareRequest,
url: baseUrl,
type: "POST",
dataType: "json"
},
destroy: {
beforeSend: prepareRequest,
url: function (data) {
return baseUrl + "(" + data.CategoryId + ")";
},
type: "DELETE",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation == "read") {
var paramMap = kendo.data.transports.odata.parameterMap(data);
delete paramMap.$format;
delete paramMap.$inlinecount;
paramMap.$count = true;
return paramMap;
} else if (operation == "create" || operation == "update") {
delete data["__metadata"];
return JSON.stringify(data);
}
}
},
batch: false,
pageSize: 10,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
sort: { field: "CategoryCode", dir: "asc" },
schema: {
data: function (data) { return data.value; },
total: function (data) { return data['##odata.count']; },
model: {
id: "CategoryId",
fields: {
CategoryId: { editable: false, type: "number" },
CategoryCode: { editable: true, type: "string", required: true, validation: { maxlength: 2 } },
Description: { editable: true, type: "string", required: true, validation: { maxlength: 50 } },
Created: { editable: false, type: "date" },
CreatedBy: { editable: false, type: "string" },
Updated: { editable: false, type: "date" },
UpdatedBy: { editable: false, type: "string" }
}
}
},
error: function (e) {
commonNotification.hide();
commonNotification.show(getRequestError(e), "error");
},
change: function (e) {
commonNotification.hide();
if (e.action == "sync") {
commonNotification.show("#SharedResources.Changes_Saved", "success");
}
},
requestStart: function (e) {
if (e.type == "read" && this.hasChanges()) {
if (confirm("#SharedResources.Dirty_Navigation_Confirmation") == false) {
e.preventDefault();
} else {
this.cancelChanges();
}
}
}
});
Generally speaking, everything works great. The prepareRequest() function is used to apply a custom authorization header as well as setting the Accept header to "application/json;odata=verbose".
When reading, the JSON response looks something like the following - this is why the dataSource.schema.data function returns data.value
{
"#odata.context":"https://localhost:44305/odata/$metadata#Categories",
"#odata.count":2,
"value":[
{
"CategoryId":1,
"CategoryCode":"01",
"Description":"Something",
"Created":"2014-08-01T11:03:30.207Z",
"CreatedBy":"DOMAIN\\User",
"Updated":"2014-09-05T14:36:22.6323744-06:00",
"UpdatedBy":"DOMAIN\\User"
},{
"CategoryId":2,
"CategoryCode":"02",
"Description":"Something Else",
"Created":"2014-08-01T11:03:35.61Z",
"CreatedBy":"DOMAIN\\User",
"Updated":"2014-08-26T16:07:29.198241-06:00",
"UpdatedBy":"DOMAIN\\User"
}
]
}
However, when I create or update an entity, the JSON returned looks like this:
{
"#odata.context":"https://localhost:44305/odata/$metadata#Categories/$entity",
"CategoryId":3,
"CategoryCode":"03",
"Description":"Yet Another",
"Created":"2014-09-06T07:55:52.4933275-06:00",
"CreatedBy":"DOMAIN\\User",
"Updated":"2014-09-06T13:55:34.054Z",
"UpdatedBy":""
}
Because this is not wrapped by "value", the Kendo grid is not updating the data source correctly. The controller that does the POST or PUT, currently returns the entity as follows:
return Created(category);
OR
return Updated(category);
I was able to fix the issue by changing the response to a JsonResult as follows:
return Json(new { value = new[] { category } });
With that, everything works as desired...however, my HTTP response is now 200 (it seems that the JsonResult will always respond with 200). In a perfect world, I could return a 201 on create. Should I just accept that I have it working and live with the 200, or, is there a simple way to respond with a 201 and still format my JSON as necessary? It seems Web API 2 allowed a more customized http response, but my web api 2.2 controller actions are returning IHttpActionResult. I really don't want to create a custom class just to have a special return type and I can't seem to return my anonymous object with Created().
In summary, I'm really leaning toward just living with what I have. However, I would be interested in a way to return my anonymous object with a 201, or, a way to accept the non-"value wrapped" json in my kendo dataSource and have it update the data appropriately.
Update Since Kendo now supports ODATA V4 there is no longer any need for tweaks to make it work.
Changing the data set type from
type: 'odata'
to
type: 'odata-v4'
Should do the trick. Example source code is here
This is what I ended up doing in the end - I made my own "CreatedObject" method that would generate a ResponseMessageResult. This would wrap the object with the anonymous "value" object and serialize to json. Then, I could return this with the desired response code.
public ResponseMessageResult CreatedObject(string location, object createdObject)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new { value = new[] { createdObject } });
// Create the response and add the 201 response code
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created);
response.Headers.Add("Location", location);
response.Content = new System.Net.Http.StringContent(json);
// return the result
return ResponseMessage(response);
}
This solved the issue for the Kendo dataSource as the client. However, I didn't like the idea of manipulating the odata response for a particular client. So, instead, I modified the client to handle the normal Web API OData response as follows:
schema: {
data: function (data) {
if (data.value) {
return data.value;
} else {
delete data["##odata.context"];
return data;
}
},
total: function (data) { return data['##odata.count']; },
model: {
etc...
Now, the schema.data() function checks to see if the object(s) are wrapped in the "value" or not before returning the appropriate data. When returning the created object, I had to remove the #odata.context attribute as kendo didn't like it.
I like the solution of manipulating this in the client much better.
One thing I had to add is a non null PK as my odata endpoint would not except null id:
parameterMap: function (data, operation) {
if (operation == "read") {
var paramMap = kendo.data.transports.odata.parameterMap(data);
delete paramMap.$format;
delete paramMap.$inlinecount;
paramMap.$count = true;
return paramMap;
} else if (operation == "create" || operation == "update") {
//delete data["__metadata"];
if (data.Id==null) {
data.Id = 1;
}
return JSON.stringify(data);
}
},

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.

Kendo DataSource with sending dynamic data to the server

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
}

Categories