kendo ui grid not showing data - asp.net-mvc

I am trying to get this basic kendo ui with expandable rows working:
<div id="grid"></div>
<script type="text/javascript">
$(function () {
$("#grid").kendoGrid({
columns: [
{
field: "ProductId",
title: "ProductId"
}
],
dataSource: {
type: "json",
transport: {
read: '#Url.Action("GetData1", "MockForms")'
}
},
height: 450,
sortable: true,
pageable: true,
detailTemplate: "<h2 style='background-color: yellow;'>Expanded!</h2>",
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
}
});
});
</script>
The json is generated like this:
public ActionResult GetData1([DataSourceRequest] DataSourceRequest request)
{
var list = new List<Product>
{
new Product {ProductId = 1, ProductType = "SomeType 1", Name = "Name 1", Created = DateTime.UtcNow},
new Product {ProductId = 1, ProductType = "SomeType 2", Name = "Name 2", Created = DateTime.UtcNow},
new Product {ProductId = 1, ProductType = "SomeType 3", Name = "Name 3", Created = DateTime.UtcNow}
};
return Json(list.AsQueryable().ToDataSourceResult(request));
}
and seems to be send OK (according to firebug). However, nothing is bound (there are no javascript errors). Any ideas?
PS:
OnaBai's 2nd comment helped me to get this to work. I changed:
return Json(list.AsQueryable().ToDataSourceResult(request));
=>
return Json(list);
which produces this JSON:
[{"ProductId":1,"ProductType":"SomeType 1","Name":"Name 1","Created":"\/Date(1371022051570)\/"},{"ProductId":1,"ProductType":"SomeType 2","Name":"Name 2","Created":"\/Date(1371022051570)\/"},{"ProductId":1,"ProductType":"SomeType 3","Name":"Name 3","Created":"\/Date(1371022051570)\/"}]
Still I would like to use:
return Json(list.AsQueryable().ToDataSourceResult(request));
as this will eventually make paging and sorting easier. It currently produces:
{"Data":[{"ProductId":1,"ProductType":"SomeType 1","Name":"Name 1","Created":"\/Date(1371022186643)\/"},{"ProductId":1,"ProductType":"SomeType 2","Name":"Name 2","Created":"\/Date(1371022186648)\/"},{"ProductId":1,"ProductType":"SomeType 3","Name":"Name 3","Created":"\/Date(1371022186648)\/"}],"Total":3,"AggregateResults":null,"Errors":null}
I tried to use:
field: "Data.ProductId",
instead of:
field: "ProductId",
in the JavaScript code with no avail.

If you want to use ToDataSourceResult you should use the ASP.NET MVC wrappers. More info is available in the documentation: http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding

Related

DataSourceResult in asp.net core

When i was worked in Asp.net Mvc , for paging data use KendoUi.this code use in Asp.net Mvc Web api
public DataSourceResult Get(HttpRequestMessage requestMessage)
{
var request = JsonConvert.DeserializeObject<DataSourceRequest>(
requestMessage.RequestUri.ParseQueryString().GetKey(0)
);
WebApplicationDbContext db = new WebApplicationDbContext();
var list = db.Product.ToList();
return list.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
}
And now working with Asp.net Core when i was use this code , it doesn't work.
in the error list show to me this error
'Uri' does not contain a definition for 'ParseQueryString' and no
extension method 'ParseQueryString' accepting a first argument of type
'Uri' could be found (are you missing a using directive or an assembly
reference?)
How can i use this code in Asp.net Core?
First remove the HttpRequestMessage requestMessage parameter. Then remove the requestMessage.RequestUri.ParseQueryString().GetKey(0) part and replace it with:
var rawQueryString = this.HttpContext.Request.QueryString.ToString();
// PM> Install-Package Microsoft.AspNetCore.WebUtilities
var rawQueryStringKeyValue = QueryHelpers.ParseQuery(rawQueryString).FirstOrDefault();
var dataString = Uri.UnescapeDataString(rawQueryStringKeyValue.Key); // this is your received JSON data from Kendo UI
I'm not sure why you need to deserialize the request. I normally pass request to ToDataSourceResult extension method.
For example,
public JsonResult Get([DataSourceRequest] DataSourceRequest request)
{
var db = new WebApplicationDbContext();
return db.Product.ToDataSourceResult(request);
}
Thank you VahidN
This project has helped me a lot
KendoUI.Core.Samples
Im use this code in Controller
public DataSourceResult GetProducts()
{
var dataString = this.HttpContext.GetJsonDataFromQueryString();
var request = JsonConvert.DeserializeObject<DataSourceRequest>(dataString);
var list = ProductDataSource.LatestProducts;
return list.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
}
And use this code in chstml
#{
ViewData["Title"] = "Home Page";
}
<!--Right to left grid-->
<div class="k-rtl">
<div id="report-grid"></div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("GetProducts", "Sample03")",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
parameterMap: function (options) {
return kendo.stringify(options);
}
},
schema: {
data: "data",
total: "total",
model: {
fields: {
"id": { type: "number" }, //Determine the field for dynamic search
"name": { type: "string" },
"isAvailable": { type: "boolean" },
"price": { type: "number" }
}
}
},
error: function (e) {
alert(e.errorThrown);
},
pageSize: 10,
sort: { field: "id", dir: "desc" },
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
$("#report-grid").kendoGrid({
dataSource: productsDataSource,
autoBind: true,
scrollable: false,
pageable: true,
sortable: true,
filterable: true,
reorderable: true,
columnMenu: true,
columns: [
{ field: "id", title: "RowNumber", width: "130px" },
{ field: "name", title: "ProductName" },
{
field: "isAvailable", title: "Available",
template: '<input type="checkbox" #= isAvailable ? checked="checked" : "" # disabled="disabled" ></input>'
},
{ field: "price", title: "Price", format: "{0:c}" }
]
});
});
</script>
}

Update Kendo Grid based On Search Form Post

I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.
Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());

Kendo UI Grid not showing JSON data

I am facing this problem for quite a while now with the problem that I am unable to bind JSON data that my controller action is passing to the kendo UI Grid, there were few JavaScript issues before but now they are gone but still my grid is not showing any results:
In Model:
public object GetResult(string id)
{
var sqlCom = new SqlCommand("SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId]=#id;", sqlConn);
sqlCom.Parameters.AddWithValue("#id", id);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
var rcrds = GETSQLRESULTS(sqlCom);
try
{
int i = 0;
if (rcrds != null || rcrds.HasRows)
{
//jsonWriter.WriteStartObject();
while (rcrds.Read())
{
jsonWriter.WriteStartObject(); //Changed
for (int j = 0; j < rcrds.FieldCount; j++)
{
jsonWriter.WritePropertyName(rcrds.GetName(j)); // column name
jsonWriter.WriteValue(rcrds.GetValue(j)); // value in column
}
i++;
jsonWriter.WriteEndObject(); //Changed
}
//jsonWriter.WriteEndObject();
}
}
catch (Exception ex) { }
return jsonWriter;
}
In Controller:
public ActionResult GetRecords()
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
//Till here jsnRslt contains this string: “{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null,"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"askjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfkl","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"safasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasf","Date":"2013-03-27T00:00:00","Height":2,"Final":0}”
//After Changes in the Model I am getting it in the required Array format:
//{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}
//{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}
//{"No":null,"Des...
return Json(jsnRslt, JsonRequestBehavior.AllowGet);
}
In View:
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
pageSize: 5,
groupable: true,
selectable: "row",
transport: { read: { url: "Records", dataType: "json"} }
},
height: 400,
scrollable: true,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ field: "No", title: " No" },
{ field: "Desc", title: "Description" },
{ field: "Date", title: "Date" },
{ field: "Height", title: "Height" },
{ field: "Final", title: "Final" }
],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
});
});
</script>
</div>
But after all this all I can see is an empty grid. And no errors in JavaScript console.
Please help
The JSON that you return from the server should be array. You currently it seems that you are returning single objects with multiple fields that are the same.
Here is an example how the JSON should look like:
[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null},
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0},
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}]
I think following code will be useful for you and let me know if you have any problem:
$('#gridName').kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
contentType: "application/json; charset=utf-8",
type: "POST",
url: 'YourURL'
}
},
pageSize: 10,
type: "json"
},
scrollable: true,
sortable: true,
resizable: true
});
Inside you dataSource set data.
data: #Html.Raw(Json.Encode(Model.RemoteObject)),
RemoteObject is you object containing all data.
First I check your tranport read URL. have you trace the controller if it fires the GetRecords command?
transport:
{
read: {
//if you don't use area then remove it
url: "#Url.Action("GetRecords", new { area = "YourAreaName", controller = "YourControllerName" })",
dataType: "json"
}
}
if it still doesn't fix your problem, then modify your Controller,
public ActionResult GetRecords([DataSourceRequest] DataSourceRequest request)
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
return Json(jsnRslt.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
here's the link to understand the Kendo's ToDataSourceResult

MVC ASP.NET - Getting jtable to call httpPost method?

I'm trying my hand at jTables with MVC 3, but have run into an issue. When my page loads, I'm not getting any calls to my [HttpPost] method. I think because of this, I keep getting the 'error connecting to database' message.
Can someone explain why my [HttpPost] method isn't getting called? Here's the relevant code:
<div id="CompetitionTable""></div>
<script type="text/javascript">
$(document).ready(function () {
//Prepare jtable plugin
$('#CompetitionTable').jtable({
title: 'The Events List',
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'Name ASC', //Set default sorting
actions: {
listAction: '#Url.Action("EventList", "CompetitionController")'
},
fields: {
EventID: {
key: true,
create: false,
edit: false,
list: false
},
EventName: {
title: 'Name',
width: '15%'
},
CompetitorEmail: {
title: 'Email address',
list: false
},
CompetitorName: {
title: 'Competitor',
width: '15%',
},
Score: {
title: 'Score',
width: '10%',
}
}
});
//Load list from server
$('#CompetitionTable').jtable('load');
});
</script>
[HttpPost]
public JsonResult EventList(int compId)
{
try
{
//Get data from database
List<Event> events = Event.getEventsByCompetitionId(compId);
//Return result to jTable
return Json(new { Result = "OK", Records = events});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
The way you call listAction is wrong. you should call it like this '/CompetitionController/EventList'
Your MVC action waits for a parameter (compId). But your lisAction does not provide that:
listAction: '#Url.Action("EventList", "CompetitionController")'
It must be something like that:
listAction: '#Url.Action("EventList", "CompetitionController")compId=5'
Probably, this table is populated dynamically for every competition and it's known on the server side. So, it must be something like:
listAction: '#Url.Action("EventList", "CompetitionController")compId=#ViewBag.compId'
Surely, you must set compId in the action of this view.

Select event on JQuery UI autocompleter is not fired

I am trying to use the jQuery UI, but I can't seem to figure out how to get the select event to execute.
I bind the autocompleter as following:
$().ready(function () {
$("#txtPersonSearch").autocomplete({
source: '<%=Url.Action("GetPeople") %>',
minLength: 3,
select: function (event, ui) {
// This code is never reached
console.log(ui);
}
});
});
Am I missing something to be able to bind to the select event?
Maybe your controller action throws an exception. Let's take the following action:
public ActionResult GetPeople(string term)
{
// the term parameter will contain the search string
// TODO: use the term parameter to filter the results from
// your repository. In this example the result is hardcoded
// to verify that the everything works.
return Json(new[]
{
new { id = "1", label = "label 1", value = "value 1" },
new { id = "2", label = "label 2", value = "value 2" },
new { id = "3", label = "label 3", value = "value 3" },
}, JsonRequestBehavior.AllowGet);
}
Things to watch out for:
The controller action is accessible with GET verb (JsonRequestBehavior.AllowGet)
The controller action returns a JSON array where each item has an id, label and value properties
The controller action doesn't throw an exception
And then:
$(function () {
$('#txtMovieSearch').autocomplete({
source: '<%= Url.Action("GetPeople") %>',
minLength: 3,
select: function (evt, ui) {
console.log(ui);
}
});
});
And finally use FireBug to analyze what exactly is sent to your server as an AJAX request and the response from the server.

Resources