Related
I'm trying to bind object to ChartJS datasets data but it's not appearing and there's no error.
Below is my C# Code:
[WebMethod]
public static List<object> GetChartData()
{
List<object> chartData = new List<object>();
List<string> labels = new List<string>();
List<int> data = new List<int>();
labels.Add("Completed jobs");
data.Add(Convert.ToInt32(90));
labels.Add("Current running jobs");
data.Add(Convert.ToInt32(10));
chartData.Add(labels.ToArray());
chartData.Add(data.ToArray());
return chartData;
}
My Client side code:
function OnSuccess_(reponse) {
var aData = reponse.d;
window.ubdChart = new Chart(t, {
type: "pie",
data: {
datasets: [{
hoverBorderColor: "#ffffff",
data: aData, // Bind int values here
backgroundColor: ["rgba(0,123,255,0.9)", "rgba(0,123,255,0.5)"]
}],
labels: ["Completed jobs", "Current running jobs"] //Bind label values here
},
}
})
};
It's working after changing the code as below.
function OnSuccess_(reponse) {
var aData = reponse.d;
console.log(aData);
window.ubdChart = new Chart(t, {
type: "pie",
data: {
datasets: [{
hoverBorderColor: "#ffffff",
data: aData[1],
backgroundColor: ["rgba(0,123,255,0.9)", "rgba(0,123,255,0.5)"]
}],
labels: aData[0]
},
options: {
legend: {
position: "bottom",
labels: { padding: 25, boxWidth: 20 }
}, cutoutPercentage: 0, tooltips: { custom: !1, mode: "index", position: "nearest" }
}
})
};
i want to send data from kendo grid to sql database, here is my javascript view model code:
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { editable: true, type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create:{
url: "/api/Companies/SaveDefCompny", // here is a correct api url, which i want to call
dataType: "json"
},
destroy: {
url: "/api/Companies/Delete",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
return kendo.stringify(data) ;
}
}
}
})
});
kendo.bind(document.getElementById("example"), viewModel);
}
Here is my controller code to post data to database but its is not calling by clicking create or update button what the problem with my grid or controller call?
[HttpPost]
public void SaveDefCompny(IEnumerable<DefCompanyDTO> DfCmpny1)
{
var result = new List<DefCompany>();
using (var data = new RPDBEntities())
{
foreach (var productViewModel in DfCmpny1)
{
var product = new DefCompany
{
Id = productViewModel.Id,
CurrentCurrencyCode = productViewModel.CurrentCurrencyCode,
ShortName= productViewModel.ShortName,
FullName= productViewModel.FullName,
ContactPerson= productViewModel.ContactPerson,
Address1= productViewModel.Address1,
CompanyCity= productViewModel.CompanyCity,
CompanyState= productViewModel.CompanyState,
CompanyCountry= productViewModel.CompanyCountry,
ZipPostCode= productViewModel.ZipPostCode,
TelArea= productViewModel.TelArea
};
result.Add(product);
data.DefCompanies.Add(product);
};
data.SaveChanges();
}
}
the url is correct but it doesnot called even while debugging cursor not goes to url but grid reads all values and display in it
As you are going to post data type: "POST" is missing in create method.
And also check posting data.models instead of data
Method resides inside Aspx page:
$("#list").jqGrid({
url: 'DirStructure.aspx/getData', //Not able get any data from here saw in firebug reponse is page itself instead of JSON data.
datatype: 'json',
mtype: 'POST',
colNames: ['pkLanguageID', 'Language'],
colModel: [
{ name: 'pkLanguageID', index: 'pkLanguageID', width: 30, align: 'left', stype: 'text', editable: false },
{ name: 'Language', index: 'Language', width: 80, align: 'left', stype: 'text', editable: true}],
rowNum: 5,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'pkLanguageID',
sortorder: 'desc',
caption: "Test Grid",
viewrecords: true,
async: false,
loadonce: true,
gridview: true,
width: 500,
loadComplete: function (result) {
alert(jQuery("#list").jqGrid('getGridParam', 'records'));
},
loadError: function (xhr) {
alert("The Status code:" + xhr.status + " Message:" + xhr.statusText);
}
});
Method resides inside DirStructure.aspx(Written WebMethod):
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
DataSet dsLang = new DataSet();
dsLang = CommonCode.CommonCode.GetIndividualLanguageList(7, 350027);
System.Diagnostics.Debug.Write(dsLang.GetXml());// Dataset for languages.
DataTable dt = dsLang.Tables[0];
System.Diagnostics.Debug.Write(GetJson(dt));
return GetJson(dt);
}
public static string GetJson(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
I degugged this I am able to get JSON data here inside method but not able to view in jqgrid.
Please help me out.
Try getting data through AJAX call then populate to the grid.
Try this :-
In Code Behind For dummy data :-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData()
{
string data = GetJson();
return data;
}
public static string GetJson()
{
List<LanguageData> dataList = new List<LanguageData>();
LanguageData data1 = new LanguageData();
data1.pkLanguageID = 1;
data1.Language = "Language1";
dataList.Add(data1);
LanguageData data2 = new LanguageData();
data2.pkLanguageID = 2;
data2.Language = "Language2";
dataList.Add(data2);
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(dataList);
}
public class LanguageData
{
public int pkLanguageID { get; set; }
public string Language { get; set; }
}
In aspx page :-
$(document).ready(function () {
GetData();
});
function GetData() {
$.ajax({
type: "POST",
url: "../DirStructure.aspx/getData",
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: false,
success: function (response) {
var item = $.parseJSON(response.d);
if (item != null && item != "" && typeof (item) != 'undefined') {
$("#list").jqGrid({
url: '../Contact.aspx/getData',
data: item,
datatype: 'local',
colNames: ['pkLanguageID', 'Language'],
colModel: [
{ name: 'pkLanguageID', index: 'pkLanguageID', width: 30, align: 'left', stype: 'text', editable: false },
{ name: 'Language', index: 'Language', width: 80, align: 'left', stype: 'text', editable: true }],
rowNum: 5,
rowList: [10, 20, 30],
pager: '#pager',
sortname: 'pkLanguageID',
sortorder: 'desc',
caption: "Test Grid",
viewrecords: true,
async: false,
loadonce: true,
gridview: true,
width: 500,
loadComplete: function (result) {
alert(jQuery("#list").jqGrid('getGridParam', 'records'));
},
loadError: function (xhr) {
alert("The Status code:" + xhr.status + " Message:" + xhr.statusText);//Getting reponse 200 ok
}
});
}
else {
var result = '<tr align="left"><td>' + "No Record" + '</td></tr>';
$('#list').empty().append(result);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
}
I'm fairly new to MVC and Jquery. for last couple of days I was trying to use Jqgrid http://www.trirand.com/blog/ to show data in my database. I use EF Code first to create my only class 'Author'
public class Author
{
public int AuthorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return FirstName+ " "+LastName ;
}
}
}
and this is my 'AuthorController' which create Json data:
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 5,
page = 1,
records = db.Authors.Count(),
rows = db.Authors.Select(a => new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I also tried different method to get my Json data:
public ActionResult LinqGridData (string sidx, string sord, int page, int rows)
{
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = (from a in db.Authors
select new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and here is my JavaScript, which I use in my view:
$(function () {
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
mtype: 'GET',
colNames:['Author ID', 'First Name', 'Last Name'],
colModel:[
{name:'AuthorID',index:'AuthorID',width:55 },
{name:'FirstName',index:'FirstName',width:90 },
{name:'LastName',index:'LastName',width:80,align:'right' }
],
pager:'#pager',
rowNum: 10,
rowList:[5, 10, 20, 30],
sortname:'AuthorID',
sortorder:'desc',
viewrecords:true,
gridview:true,
caption:'Author List'
});
});
jQuery("#datagrid").jqGrid('navGrid', '#navGrid', { edit: true, add: true, del: true });
I can show the grid with dummy data. with this action method:
public ActionResult GridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 1, // we'll implement later
page = 1,
records = 3, // implement later
rows = new[]
{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is that a good question?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky in the sky?"}}
}
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
the problem is whenever I want to show the data from my database, I only can show the grid itself not the data.
I tried to convert the json data toList() or toArary() before sending to the view, same result. I hope I made myself clear.
any help would be much appreciated.
Have you tried jsonReader with "repeatitems: false" ?
For example:
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
jsonReader: {
repeatitems: false
},
.....
UPDATE:
If you look at the response body returned from your LinqGridData method, it looks like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"AuthorID":"1","FirstName":"Mike","LastName":"Lee"}}, .....
]
}
But I think it should be like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"1", "Mike", "Lee"}}, .....
]
}
Actually this is your "dummy data" version's response body.
I'll post my working example below. In this example, I did not use 'cell' attribute.
At server side:
var myQuery = from t in db.Customers
select t;
var jsonData = new
{
total = totalPages,
page = pageNum,
records = totalRecords,
rows = myQuery.ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
At client side:
{
url: '#Url.Action("GetList")',
datatype: 'json',
jsonReader: {
repeatitems: false
},
mtype: 'GET',
colModel: [
{
name: 'CustomerID', label: 'ID', hidden: false, width: 40, sortable: true
},
{
name: 'CompanyName', label: 'Company', width: 100, align: 'center'
},
]
}
Hope this helps.
I finally managed to show data from my db. the problem was in my query. i use this method for my action method:
public JsonResult LinqGridData (string sidx, string sord, int page, object rows)
{
var authors = (from a in db.Authors select a).ToList();
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = authors.Select(a => new
{
id = a.AuthorID,
cell = new[] { a.AuthorID.ToString(), a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and i used this in my Javascript:
$(function () {
$("#list").jqGrid({
url: "/Author/LinqGridData",
datatype: "json",
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id:"id"
},
mtype: "GET",
colNames: ["Author ID", "First Name", "Last Name"],
colModel: [
{ name: "AuthorID", key: true, width: 55 },
{ name: "FirstName", width: 80 },
{ name: "LastName", width: 100, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [5, 10, 20],
sortname: "AuthorID",
sortorder: "desc",
viewrecords: true,
gridview: true,
width: 610,
height: 250,
caption: "Author List"
});
});
jQuery("#list").jqGrid("navGrid", "#pager", { edit: true, add: true, del: true });
yes , you can omit the 'cell' attribute and reduce your json data. you can also put 'id':0 which normally means treat the first item as the id. i also used 'key' attribute, but it's redundant. you can also pass your query result as Array too. if anyone can tell me is there any benefit of using List over others would much appreciated.
Thanks for your help
good luck
Script:
jQuery("#grid_table").jqGrid({
url: '#Url.Action("GetAll", "Widget")',
datatype: "json",
mtype: 'GET',
colNames: ['id', 'name'],
colModel: [
{ name: 'id', index: 'id', width: 55, sortable: true, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'name', index: 'name', width: 200, editable: true }
],
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "id",
userdata: "userdata"
},
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery('#gridpager'),
sortname: 'name',
viewrecords: true,
sortorder: "asc",
caption: "Wines"
}).navGrid('#gridpager');
Controller:
public ActionResult GetAll()
{
List<object> list = new List<object>();
for (int i = 0; i < 20; i++)
{
var o = new
{
id = i.ToString(),
name = "name " + i.ToString()
};
list.Add(o);
}
var result = new
{
page = "1",
total = "1",
records = "10",
rows = list.ToArray()
};
string Jlist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
return Json(Jlist, JsonRequestBehavior.AllowGet);
}
Json output:
And message: No records found!
What is the wrong with my code?
Thanks.
I think as mentioned in your json reader "userdata" is not there in your json .
So please pass some null value or any value in your userdata field.
Problem is this line:
string Jlist = Newtonsoft.Json.JsonConvert.SerializeObject(result);
I removed serilization line and then it works. Thanks for reply.