Binding a Model class object to Kendo Grid using JSON result - javascript

I need to bind a Kendo grid to a model class. I am returning the same from controller using Json result but the gird is not getting bind. Also find below code snippets used.
Model:
public DataTable ErrorData { get; set; }
public List<string> Groups { get; set; }
public Dictionary<string, System.Type> ErrorColumns { get; set; }
Controller :
public JsonResult PopulateData()
{
ErrorPage _objError = new ErrorPage();
//Getting the details from Database
_objError.ErrorData = dbl.GetDataTable(DbConnectionString,Table,whereCondition, columns);
//Poplulating the Column list as it is dynamically generated every time as per the filter on front end(View)
//Column description: Name and Type
var columnlist = new Dictionary<string, System.Type>();
foreach (System.Data.DataColumn column in _objError.ErrorData.Columns)
{
var t = System.Type.GetType( column.DataType.FullName );
columnlist.Add(column.ColumnName, t);
}
_objError.ErrorColumns = columnlist;
return Json(_objError);
}
View:
This is a code return on button click
$.post(path, { application: app, columns: columns, machine: machine, pages: pages,
startDate: startDate, endDate: endDate }, function (result) {
var grid = $("#ErrorLog").data(result);
grid.dataSource.read();
grid.refresh();
});
This is Kendo grid code which also get bind to data on page load:
#(Html.Kendo().Grid<dynamic>()
.Name("ErrorLog")
.Columns(columns =>
{
//Define the columns
foreach (var c in Model.ErrorColumns)
columns.Bound(c.Value, c.Key);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
foreach (System.Data.DataColumn column in Model.ErrorData.Columns)
{
model.Field(column.ColumnName, column.DataType);
}
})
.Read(read => read.Action("populateData", "Common"))
)
.Groupable()
.Sortable(s => s.AllowUnsort(true))
.Filterable(ftb => ftb.Mode(GridFilterMode.Menu))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
//.ButtonCount(5)
)
)
The column list is populated properly. but i am not sure about the returning the JsonResult to a kendo grid. Kindly help on how to bind a kendo grid using Json result.

Here we go with the solution:
This is my controller where i have serialized the object we are trying to send to View:
public JsonResult populateData(string application, string columns, string machine, string pages, string startDate, string endDate)
{
ErrorPage _objError = new ErrorPage();
var ErrorResult = _objError.GetErrorData(application, columns, machine, pages, startDate, endDate);
//Column description: Name and Type
var columnlist = new Dictionary<string, System.Type>();
foreach (System.Data.DataColumn column in _objError.ErrorData.Columns)
{
var t = System.Type.GetType(column.DataType.FullName);
columnlist.Add(column.ColumnName, t);
}
_objError.ErrorColumns = columnlist;
var result = JsonConvert.SerializeObject(ErrorResult.ErrorData, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is my view which binds the datatable send from controller to Kendo grid:
$.ajax({
type: "POST",
url: '#Url.Content("~/Common/PopulateData")',
contentType: "application/json;charset=utf-8",
dataType: 'json',
data: JSON.stringify({ application: app, columns: columns, machine: machine, pages: pages, startDate: startDate, endDate: endDate }),
success: function (data) {
$('#ErrorLog').data("kendoGrid").dataSource.data(JSON.parse(data));
}
});
Thanks

Related

How display ajax data in select2.js v4.0?

I am using select2 v4.0 https://select2.github.io/ in an asp mvc project and I want display a simple dropdown from dynamic Data
The old way of version 3.6 doesn't work anymore:
I have a c# methode:
public JsonResult GetSrcMethod()
{
var list = new[]
{
new { id= 0, text= "Smith" },
new { id= 1, text= "John" },
new { id= 2, text= "Philippe" },
}.ToList();
Object json = JsonConvert.SerializeObject(list);
return Json(json, JsonRequestBehavior.AllowGet);
}
Thus, the data returned is:
[{"id":0,"text":"Smith"},{"id":1,"text":"John"},{"id":2,"text":"Philippe"}]
And I have a javascript code which worked on previous version 3.6:
$(".example-select2").select2({
ajax: {
dataType: 'json',
url: '#Url.Action("GetSrcLanguages", "GetCheckSet")',
results: function (data) {
return {results: data};
}
}
});
It render an empty dropdownlist that displays 'No result found'
Do you know how to do it in v4.0?
Id is not the same as id, properties on JavaScript objects are case-sensitive. The same applies to Text and text as well, you want to use the all-lowercase versions.
public JsonResult GetSrcLanguages()
{
var list = new[]
{
new { id = 0, text = "Smith" },
new { id = 1, text = "John" },
new { id = 2, text = "Philippe" },
}.ToList();
Object json = JsonConvert.SerializeObject(list);
return Json(json, JsonRequestBehavior.AllowGet);
}
Also, the ajax.results method was renamed to ajax.processResults in 4.0.0 to avoid conflicting with AJAX transports that have an existing results method. So your JavaScript should actually look like
$(".example-select2").select2({
ajax: {
dataType: 'json',
url: '#Url.Action("GetSrcLanguages", "GetCheckSet")',
processResults: function (data) {
return {results: data};
}
}
});

Flot Chart Conversion C# Javascript/AJAX - Bar Chart

I am trying to convert a C# list object to the correct format for a Flot Bar chart. For some reason I just can't seem to get it done correctly. I have tried several different methods. The JSON I am returning is valid JSON and the list is valid but for some reason the Flot chart wants the data in a different format. Any help would be appreciated. Thank you!
Here is the converted C# List to JSON Array
[{"color":"red","data":["Agriculture",0,2]},{"color":"red","data":["Healthcare",0,1]},{"color":"red","data":["Manufacturing",0,0]},{"color":"red","data":["Retail",0,0]},{"color":"red","data":["Information Technology",0,0]}]
I use this method to do so:
$.ajax({
type: "POST",
url: "Summary.asmx/getBarChartSeriesData",
data: JSON.stringify({ userid: userid }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
barSummaryData = response.d;
var jsonArray = JSON.parse(response.d);
//this format seems to work
//var data = [{ data: [[0, 1]], color: "red" }, { data: [[1, 2]], color: "yellow" }, { data: [[2, 3]], color: "green" }];
var plot =
$.plot($('#barSummaryPlaceholder'), jsonArray, {
series: {
bars: {
show: true,
barWidth: 0.3,
align: "center"
}
},
xaxis: {
ticks: ticks
},
grid: { hoverable: true, clickable: true }
});
},
failure: function (msg) {
$('#barSummaryPlaceholder').text(msg);
}
});
Here is the C# Method in the ASMX:
public string getSummaryBarChartSeriesData(int userid)
{
List<Series> SeriesData = new List<Series>();
DataTable dt = new DataTable();
dt.Clear();
dt = chartcode.RetrieveSummaryBarChartData(userid);
int countOfRows = 0;
foreach (DataRow row in dt.Rows)
{
List<object> objData = new List<object>();
objData.Add(row["Name"].ToString());
objData.Add(countOfRows);
objData.Add(Convert.ToInt32(row["CountOfStudents"]));
SeriesData.Add(
new CareerClusterSeries
{
data = objData,
color = "red"
});
}
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(SeriesData);
return json;
}
For some reason the C# json string is in the valid format for JSON itself but NOT the correct format for Flot charts which is the chart system I am trying to use.
First, from the documentation Flot Reference: Data Format, the data field should be an array of arrays of numbers, e.g.:
{
label: "y = 3",
data: [[0, 3], [10, 3]]
}
In contrast, you have an flat array of numbers with a string mixed in: {"data":["Agriculture",0,2], "color":"red",}. What is the purpose of the string -- is it the series label?
Next, did you forget to increment countOfRows? It's always zero in your code.
Assuming you wanted to increment the count and set row["Name"] to be the series label, the following should produce JSON that complies with the API:
public class Series
{
public string color { get; set; }
public List<IList<double>> data { get; set; }
public string label { get; set; }
}
And then:
public string getSummaryBarChartSeriesData(int userid)
{
var SeriesData = new List<Series>();
DataTable dt = chartcode.RetrieveSummaryBarChartData(userid);
int countOfRows = 0;
foreach (DataRow row in dt.Rows)
{
var rawData = new List<IList<double>>();
rawData.Add(new double[] { countOfRows++, Convert.ToInt32(row["CountOfStudents"]) });
//objData.Add(row["Name"].ToString());
SeriesData.Add(
new CareerClusterSeries
{
data = rawData,
color = "red",
label = row["Name"].ToString(), // Guessing you wanted this.
});
}
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(SeriesData);
return json;
}

Iterate on a JSON in JavaScript Asp.net

I have following data that I have serialized as JSON from my code behind file.
public class PieModel {
public string label { get; set; }
public double data { get; set; }
}
var data = new List<PieModel> {
new PieModel { label = "Pending", data = 10d }
new PieModel { label = "New", data = 40d }
new PieModel { label = "Overdue", data = 50d }
};
hdnData.Value = new JavaScriptSerializer().Serialize(data);
I read this serialized data in JavaScript like this
var tempHdnData = $("#hdnData");
But now I want to iterate on tempHdnData and get label and data members separately in JavaScript code. How can I achieve that?
You could write your code like this in the code behind:
protected List<PieModel> GetData() {
return new List<PieModel> {
new PieModel { label = "Pending", data = 10d }
new PieModel { label = "New", data = 40d }
new PieModel { label = "Overdue", data = 50d }
};
}
And in your webform:
var tempHdnData = <%= new JavaScriptSerializer().Serialize(GetData()) %>
Now you can write
$.each(tempHdnData, function (_, data) {
console.log(data)
})

Jquery JTable Load from 2 Tables

I am using Jquery-JTable in my website to load details in a grid view and to let user be able to modify, delete app accordingly.
I am loading data successfully from 2 tables and then display them in my div. Now the user would like to modify a record accordingly to his/her wish.
I would like to let the user choose from a dropdown list obtained from another table. Can this be done?
Code Below: As you can see I am loading data from multiple tables using InnerJoin. For example I would like to let the user choose another Category or Language etc.
$queryString = "SELECT `app_id`,`app_name`,`app_type`,`app_url`,`AppAccepted`,`BenefitApp`, application_ageGroup.ageGroup,application_category.category, application_Country.country,application_Language.language FROM application INNER JOIN application_ageGroup ON application.ageGroup_id = application_ageGroup.ageGroup_id INNER JOIN application_category ON application.Category = application_category.category_id INNER JOIN application_Country ON application.country_id = application_Country.country_id INNER JOIN application_Language ON application.language_id = application_Language.language_id ORDER BY $jtSorting LIMIT $jtStartIndex,$jtPageSize";
Regards,
Make the Category column as dropdown and bind it with your query dataset :
$('#Table').jtable({
paging: true,
pageSize: 200,
sorting: true,
defaultSorting: 'Category ASC',
selecting: false,
multiselect: false,
selectingCheckboxes: false,
actions: {
listAction: '/Application/GetData',
updateAction: '/Application/EditData'
},
fields: {
Category: {
title: 'Category',
width: '10%',
list: false,
sorting: true,
options: '/Application/GetCategories'
}
});
In your controller action, fetch Category lists:
[HttpPost]
public JsonResult GetCategories()
{
try
{
DataTable dtCategories = new DataTable();
string query = "SELECT .....";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
dtCategories.Load(command.ExecuteReader());
}
List<Store> categoryList = DatatableToGenericList(dtCategories);
var categories = categoryList.Select(category => new { DisplayText = category.Name , Value = category.Id }).OrderBy(s => s.DisplayText);
return Json(new { Result = "OK", Options = categories });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
private static List<Store> DatatableToGenericList(DataTable table)
{
var categoryList = new List<Category>(table.Rows.Count);
foreach (DataRow row in table.Rows)
{
var values = row.ItemArray;
var store = new Category()
{
Id = values[0].ToString(),
Name = values[1].ToString()
};
categoryList.Add(store);
}
return categoryList;
}
Category Model
public class Category
{
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
Hope this helps..

Web API string parameters and POST values

I am using a jQuery plugin, jTable. The plugin has the following function to load the table:
$('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' });
The values in the load function is send as POST data. The plugin also sends two query string parameters (jtStartIndex, jtPageSize) through the URL for paging the table.
An example in the documentation shows a function on how to handle this in ASP.NET MVC but not in Web API Example :
[HttpPost]
public JsonResult StudentListByFiter(string name = "", int cityId = 0, int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
try
{
//Get data from database
var studentCount = _repository.StudentRepository.GetStudentCountByFilter(name, cityId);
var students = _repository.StudentRepository.GetStudentsByFilter(name, cityId, jtStartIndex, jtPageSize, jtSorting);
//Return result to jTable
return Json(new { Result = "OK", Records = students, TotalRecordCount = studentCount });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
How my function currently looks: It works fine except that I can't manage to read the POST data (name param):
public dynamic ProductsList(string name = "", int jtStartIndex = 0, int jtPageSize = 0 )
{
try
{
int count = db.Products.Count();
var products = from a in db.Products where a.ProductName.Contains(name) select a;
List<Product> prods = products.OrderBy(x => x.ProductID).ToList();
return (new { Result = "OK", Records = prods, TotalRecordCount = count });
}
catch (Exception ex)
{
return (new { Result = "ERROR", Message = ex.Message });
}
}
My jTable load: (This get called when the user enters text in a input)
$('#ProductTable').jtable('load', {
name: $('#prodFilter').val()
});
I would appreciate any help with how to read both the string parameters in the URL and the POST data in a Web API function.
EDIT:
I used an alternative way to send the data to the API. Instead of sending it in the load function formatted as JSON I used a function for the listAction and sent the data through the URL (See jTable API reference for details):
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: 'http://localhost:53756/api/Product/ProductsList?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&name=' + $('#prodFilter').val(),
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
To reload the table based on your filtered results:
$('#ProductTable').jtable('load');
Instead of this:
$('#ProductTable').jtable('load', {
name: $('#prodFilter').val()
});
Try applying the [FromBody] attribute to the name parameter
public dynamic GetProductList([FromBody]string name = "", int jtStartIndex = 0, jtPageSize = 0)
{
...
}
The default binder in Web API will look in the URI for simple types like string, specifying the FromBody attribute will force it to look in the body.

Categories