Create chart with serverside object data using JSON - c#

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);
}
});
});

Related

Passing JSON to WebApi in MVC5

im facing issues in syntax to pass json array from jquery to the webapi in my mvc5 project .
Following is my code :-
C# code:-
//GET Instance
// GET: api/PostDatas
public IQueryable<PostData> GetPostDatas()
{
return db.PostDatas;
}
//POST Instance
// POST: api/PostDatas
[ResponseType(typeof(PostData))]
public IHttpActionResult PostPostData(PostData postData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PostDatas.Add(postData);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = postData.postDataID }, postData);
}
JQuery
<script>
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
</script>
Im not able to send the data using jquery to my c# controller , just need to understand the syntax . Thank you .
check following things in your code:
1) Method attribute [HttpPost]
2) [FromBody] for input model
3) Check PostData class, it should contain public properties for userid, Description and photoid with case-sensitive of variable names.
and mainly change your AJAX request code to:
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: JSON.stringify(model), //i have added JSON.stringify here
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
Please let me know, is this works for you?
I included [FromBody] in the parameter in my previous project.
Something like this:
[HttpPost]
public IHttpActionResult Register([FromBody]PostData postData)
{
// some codes here
}
I was able to read the JSON data from that notation.

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.

Issue parsing JSON with JQuery

I am trying to parse a JSON object passed from a WCF Service, here is the Response the service gives
[
{
"Caption": "Hello",
"CityState": "Seattle",
"URL": "Test"
},
{
"Caption": "World",
"CityState": "Chicago",
"URL": "Test"
},
{
"Caption": "Hello",
"CityState": "New York",
"URL": "Test"
}
]
Here is the WCF Code to create the object
///Custom Object has 3 string properties
List<OW_CompanyACSearch> search = new List<OW_CompanyACSearch>();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<OW_CompanyACSearch>));
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, search);
return Encoding.Default.GetString(stream.ToArray());
}
and here is the JQuery that I am trying to make work
source: function (request, response) {
j$.ajax({
url:"testservice.svc",
dataType: "json",
data: {
Search: request.term
},
success: function (data) {
response(j$.map(data, function (item) {
return {
label: item.Caption,
value: item.Caption,
URL: item.URL,
CityState: item.CityState
}
}));
}
});
}
The issue that I am having is that when I fall into the return to parse the members on the object, none of the properties are defined. If I drill down into the object, it seems that it is treating object as one long string, so index[0] would be "[" and so on.
I have read all over and I have tried every option that I have seen and I still get this issue. I am not sure if I am serializing or parsing incorrectly, but any help would be appreciated.
Also, not sure if it matters, but the binding on the WCF is webHttpBinding
Wow this was awesome, come to find out that data was just a wrapper for the JSON object, and there was a property named "d" that was the actual object.
So this
data = j$.parseJSON(data.d);
filled data with the object, and I could move forward.
The data object should already be a variable array that contains your data at the properties as named by the JSON. You should be able to do something like this:
source: function (request, response) {
j$.ajax({
url:"testservice.svc",
dataType: "json",
data: {
Search: request.term
},
success: function (data) {
alert(data[0].Caption);
}
});
}
To verify the object structure.

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