Kendo Grid has correct JSON but data not showing up - asp.net-mvc

I'm trying to use Teleric's Kendo Grid in ASP.NET MVC 5. I'm following the example here, but the grid is not populating with data. The columns show up, but it says "No items to display".
http://docs.telerik.com/kendo-ui/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
This is my Words/Read function:
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var items = db.Words.Take(1).ToList();
//this code was necessary to get the correct JSON result
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var converted = JsonConvert.SerializeObject(items, null, jsSettings);
return Content(converted);
}
I got the following JSON result from Words/Read:
[{"WordId":1,"Rank":1,"PartOfSpeech":"article","Image":"Upload/29/1/Capture1.PNG","FrequencyNumber":"22038615","Article":null,"ClarificationText":null,"WordName":"the | article","MasterId":0,"SoundFileUrl":"/UploadSound/7fd752a6-97ef-4a99-b324-a160295b8ac4/1/sixty_vocab_click_button.mp3","LangId":1,"CatId":null,"IsActive":false}]
Finally, my view page:
#(Html.Kendo().Grid<NextGen.Models.Word>
()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
.Read(read => read.Action("Read", "Words"))
)
.Columns(columns =>
{
columns.Bound(c => c.WordName);
columns.Bound(c => c.PartOfSpeech);
})
.Pageable()
.Sortable()
)
I've seen some similar questions to this one, but most are using Javascript rather than Html helpers. Am I doing something dumb?

I found an alternative way to get around the circular reference problem I was having. Basically, the answer is here: A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.
For people with the same problem: I took the two properties I needed - WordName and PartOfSpeech, and passed only those attributes to the toDataSource function Kendo provides.
My new read function looks like this:
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var items = db.Words.Select(w => new WordL{
WordName = w.WordName,
PartOfSpeech = w.PartOfSpeech
});
return Json(items.ToDataSourceResult(request));
}
where WordL is a model with just PartOfSpeech and WordName attributes, rather than all the attributes of my class.

It is probably because you are not using 2 methods in your controller. While your page view is first ActionResult you should use second one as in the grid as you did in your example. I hope it is obvious.
public ActionResult ReadPage()
{
return View();
}
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{
var items = db.Words.Take(1).ToList();
//this code was necessary to get the correct JSON result
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var converted = JsonConvert.SerializeObject(items, null, jsSettings);
return Content(converted);
}

Related

Kendo Grid Inline Editing Get current row data when updating

I am using Inline editing in a Kendo Grid and I want to be able to get the current row data when doing an update.
Html.Kendo().Grid<WheresMyTool.Models.COMPANYADDRESS>()
.Name("ShipToLocationsGrid")
.Editable(editable => editable.Mode(Kendo.Mvc.UI.GridEditMode.InLine))
.Pageable(pager => pager.PageSizes(new List<object> { 5, 10, 20, 100 }))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.COMPANY))
.Read(read => read.Action("IndexShipToLocations", "Company", new { company = Model.company }))
.Update(update => update.Action("ShipToLocations_Update"))
.PageSize(20)
)
Here is my update method
public ActionResult ShipToLocations_Update([DataSourceRequest] DataSourceRequest request, COMPANYADDRESS ca)
{
Repository repo = new Repository();
repo.UpdateCompanyAddressRecord(ca, username);
return Json(ca);
}
I want to be able to access the current data. It seems like only the modified data is passed in.
[HttpPost]
public ActionResult EditTestStationInLine([DataSourceRequest] DataSourceRequest request, TestStationViewModel tsvm)
{
if(tsvm != null && ModelState.IsValid)
{
TestStation ts = _testStationService.Find(tsvm.Id);
ts.ProductionLineId = tsvm.ProductionLineId;
ts.ProdLine = _productionLineService.Find(tsvm.ProductionLineId);
ts.Name = tsvm.Name;
_testStationService.Update(ts);
tsvm.Id = ts.Id;
tsvm.ProductionLineId = ts.ProductionLineId;
}
return this.Json(new[] { tsvm }.ToDataSourceResult(request, ModelState));
}
This is an example of one of my InLine edits. Your view model is used to create a database model. Once your database model is created, you can pass back the hidden attributes, in my case the Id and CreateAt. Hope this helps answer your question.
Edit:
function Edit(e) {
var grid = $('#NAMEOFKENDOGRID').data('kendoGrid');
var dataItem = grid.dataItem($(e.target).parents('tr'))
var id = dataItem.id;
$.ajax({//Makes an ajax call
success: function (data) {
$('#NAMEOFDIV').load("/Controller/Update/" + id);
}
});
}
You can make a custom command, conveniently called Edit, which then gets the Id from that row. It also makes an ajax call to your update method. Modify the ajax to fit your needs.

Kendo Drop Down List not showing data

I am trying to create a Kendo Dropdownlist and it will not call the read.Action for some reason. I cannot figure out what I am missing.
I have set the read.Action to different methods and it works but it just will not call it to this specific method. I have verified that I am spelling it correctly and I've set breakpoints on everything to find what it runs.
#(Html.Kendo().DropDownList()
.Name("productionline-dropdown")
.DataTextField("Id")
.DataValueField("Name")
.DataSource(source =>
{
source.Read(read => { read.Action("GetDropDownList", "Home"); });
})
)
[HttpPost]
public JsonResult GetDropDownList()
{
var productionLines = _productionLineService.GetAll().Select(x => new ProductionLineViewModel
{
Id = x.Id,
Name = x.Name,
CreatedAt = x.CreatedAt,
UPE = x.UPE,
ComputerName = x.ComputerName,
ActiveLine = x.ActiveLine
});
return Json(productionLines, JsonRequestBehavior.AllowGet);
}
I want my DropDownList to populate with the Names of the ProductionLines not the Ids. Thanks
This is because the action is decorated with HttpPost, while the control apparently sends Get (quite logically) to fetch the data. Remove this attribute, and that should fix it.

Grid does not call action method to fill data in IE

Can someone help me to resolve the issue of filling Kendo UI Grid in mvc on IE platform?
The following are technologies used:
1) Telerik Kendo UI version 2015.1.408.545
2) MVC 5.0, razor view
3) .Net Framework 4.5
In Chrome whenever MVC View page loads it calls read action method twice. First call is for getting scema to be bind to the Kendo UI Grid. Second time is for getting data to fill Kendo UI Grid. All this requests from Controller to View and vice versa works fine in Chrome.
But when I run this application in IE (11.0), then first time it displays all the data properly. But when the request posted for another data it does not call the action method twice. Therefore the previous data is being displayed on Grid. Thats the issue.
View
#model CustomReportResultsViewModel
#(Html.Phoenix().Grid<DataTable, DataTable>()
.DataSourceReadController("CustomReport", "Reports")
.KeyName("ID")
.RecordName(Model.RecordName)
.CacheEditorTemplate(false)
.Columns(columns => { foreach (DataColumn c in Model.DataTable.Columns) { }})
)
Controller
public ActionResult ResultsGrid(int id, string recordName) {
return PartialView("ResultsGrid", new CustomReportResultsViewModel { DataTable = GetData(id, true), RecordName = recordName });
}
// List
public JsonResult Read([DataSourceRequest] DataSourceRequest request)
{
var table = GetData();
var result = table.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet, 3);
}
private string GetDataSource(StringBuilder columnSchema, StringBuilder aggregates, StringBuilder group, string primaryKey, string read) {
var dataSource = new StringBuilder();
dataSource.Append("{transport:{"); dataSource.Append("read:{type:\"GET\",url:\"" + read + "\"}"); dataSource.Append("},");
dataSource.Append("type:\"aspnetmvc-ajax\",");
}
How do you request the data? AJAX call? Would be better if you added the grid datasource code / controller methods. Narrow the question, please.
This grid/controller signatures always worked for me on IE.
Controller:
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetData([DataSourceRequest] DataSourceRequest request)
{
//whatever it takes to get that data, like
var data = repository.GetAll<Model>();
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
View:
#using Entites.Model
#(Html.Kendo().Grid<Model>()
.Name("grid")
.DataSource(dataSource =>
{
dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("GetData", "Home"));
})
)
Thanks for your quick reply.
We are following the below code:
public ActionResult ResultsGrid(int id, string recordName)
{
return PartialView("ResultsGrid", new CustomReportResultsViewModel { DataTable = GetData(id, true), RecordName = recordName });
}
// List
public JsonResult Read([DataSourceRequest] DataSourceRequest request)
{
var table = GetData();
var result = table.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet, 3);
}
private string GetDataSource(StringBuilder columnSchema, StringBuilder aggregates, StringBuilder group, string primaryKey, string read)
{
var dataSource = new StringBuilder();
dataSource.Append("{transport:{");
dataSource.Append("read:{type:\"GET\",url:\"" + read + "\"}");
dataSource.Append("},");
dataSource.Append("type:\"aspnetmvc-ajax\",");
}

Getting Kendo treeview to work

So I'm trying to get a simple Kendo treeview to bind to JSON data but I am having a hard time. Any ideas why this isn't working? I put a break point on my JSON result code, but it never even fires.
My HTML:
#(Html.Kendo().TreeView()
.Name("treeview")
// The property that specifies the text of the node
.DataTextField("Name")
.LoadOnDemand(true)
.DataSource(dataSource => dataSource
.Read(read => read
// The action method which will return JSON
.Action("ReadCats", "Entity")
.Data("Id")
)
)
)
My Controller:
public JsonResult ReadCats(int? id)
{
var categories = _entityLogic.GetActiveCategories();
var jsonResult = categories.Select(cat => new
{
Id = cat.Id,
Name = cat.Name,
HasChildren = categories.Where(c => c.ParentCategory == cat.Id).Any(),
ParentId = cat.ParentCategory
}).ToList();
return Json(jsonResult, JsonRequestBehavior.AllowGet);
}
Now if I browse to myapplication/Admin/Entity/ReadCats, I do get the JSON data back. Like I said though, the breakpoint never hits when I load the view the tree is on.
Any ideas? I'd note that I've tried every variation of .Action("ReadCats", "Entity") I can think of like: .Action("ReadCats", "/Admin/Entity"), .Action("ReadCats", "~/Admin/Entity"), etc.

Auto-generate grid columns with collection of dynamic objects as model in Telerik MVC grid

My model is an IEnumerable which I would like to bind to a telerik mvc grid. Additionally the grid should auto-generate the columns and display everything from my dynamic object.
I found several posts on the telerik forum regarding this topic, like here: http://www.telerik.com/community/forums/aspnet-mvc/general/dynamically-generate-grid-columns.aspx
Unfortunately the result is the same: the grid displays the number of total rows in the footer but no rows are shown.
Any ideas?
Update: I attached a sample project on the telerik forum: http://www.telerik.com/community/forums/aspnet-mvc/grid/auto-generate-grid-columns-with-collection-of-dynamic-objects-as-model.aspx
Update: Here's sample code to try it out:
Index.cshtml:
#model IEnumerable<dynamic>
#(
Html.Telerik().Grid(Model).Name("Grid")
.Columns(columns => columns.AutoGenerate(true))
.Pageable()
.Sortable()
.Groupable()
.Filterable()
)
HomeController.cs:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(GetStaticData());
}
private static IEnumerable<dynamic> GetStaticData()
{
dynamic products = new[]
{
new { ProductID = 1, ProductName = "Motor" },
new { ProductID = 2, ProductName = "Converter" },
new { ProductID = 3, ProductName = "Transformer" }
};
return products;
}
}
This post seems to say that it's not supported.
http://www.telerik.com/community/forums/aspnet-mvc/grid/display-dynamic-objects-in-grid.aspx
This post says that you can overload the columns binding and passing in the propery name.
http://www.telerik.com/community/forums/aspnet-mvc/grid/dynamic-view-with-grid.aspx
Looks like you can use dynamic data but not auto generated columns.
Thanks,

Resources