telerik ASP.net MVC Grid Ajax binding issue - ajax

I compared the codes with Telerik sample , everything is the same except the model. But I can't see the records in Grid.
// Controller
public ActionResult Index()
{
return View();
}
[GridAction]
public ActionResult _Index()
{
return View(new GridModel<AuctionViewModel>
{
Data = GetData()
}
);
}
// If I replace 'Index' Action codes with '_Index' , the server binding works fine and shows the records but when I try to run AjaxBinding , It doesn't works (never runs _Index codes)
// View
#model List<TestMVC3_Telerik.Models.AuctionViewModel>
#{
Html.Telerik().Grid((List<TestMVC3_Telerik.Models.AuctionViewModel>)ViewData["MyAuctions"])
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.AuctionID).Title("ID").Width(100);
columns.Bound(o => o.AuctionName).Title("Name");
})
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Index", "Grid"))
.Pageable(paging => paging.PageSize(5))
.Sortable()
.Scrollable()
.Groupable()
.Filterable();
}

.DataBinding(dataBinding => dataBinding.Ajax().Select("_Index", "Grid"))
Change "Grid" to what you are calling the page from
.DataBinding(dataBinding => dataBinding.Ajax().Select("_Index", "Home"))
Once I did that it loaded for me.

Related

Telerik.UI.for.AspNet.Core in MVC Cannot display data in Grid from a DB context

I think I'm close. Its not throwing any errors but its also not displaying any data... Im just trying to get it to display a list of Company Names and Company IDs from my TblCompanyInfo table.
This is my controller:
public async Task<IActionResult> Index()
{
var apptReminderContext = _context.TblCompanyInfos.Include(t => t.AcctType).Include(t => t.CompanyStatus).Include(t => t.OnHoldReason);
return View(await apptReminderContext.ToListAsync());
//return View();
}
public JsonResult Products_Read([DataSourceRequest] DataSourceRequest request)
{
DataSourceResult result = _context.TblCompanyInfos.ToDataSourceResult(request,
model => new TblCompanyInfo
{
CompanyId = model.CompanyId,
CompanyName = model.CompanyName
});
return Json(result);
}
and my view...
#model IEnumerable<AppointmentRemindersNetCoreMVC.Models.TblCompanyInfo>
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
#using AppointmentRemindersNetCoreMVC.Data
#using Kendo.Mvc.UI
#addTagHelper *, Kendo.Mvc
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#Html.AntiForgeryToken()
#(Html.Kendo().Grid<AppointmentRemindersNetCoreMVC.Models.TblCompanyInfo>()
.Name("grid")
.DataSource(dataSource => dataSource.Ajax()
.Read(read => read.Action("Products_Read", "Company"))
.PageSize(20)
//.ServerOperation(false)
//.Model(model => model.Id(c => c.CompanyId))
//.Read("Products_Read", "Company")
//.Read(read => read.Action("Products_Read", "Company"))
.Update("UpdateCustomer", "Home")
.Create("InsertCustomer", "Home")
.Destroy("DeleteCustomer", "Home"))
.Columns(columns =>
{
columns.Bound(product => product.CompanyName);
columns.Bound(product => product.CompanyId);
})
.Pageable()
.Sortable()
)
Also I know that the Products_Read function is being called by the view and I also know that the "result" contains 32 rows of data. However, nothing is displayed in the grid.
Figured it out! Turns out that json camelcases the return string so the model properties did not match what was returned by json. The solution was to add this line to the Startup.cs file.
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.PropertyNamingPolicy = null);

Kendo UI does not call the READ call

I am having an issue where the READ operation for the Kendo Grid does not get invoked and hence the grid does not populate any data. I have followed these links
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/troubleshooting#the-ajax-bound-grid-does-not-populate
Kendo UI Grid is not calling READ method
However the issue still exists.
/// CS File
public ActionResult GetItemsHome([DataSourceRequest] DataSourceRequest request , int page)
{
List<CustomItem> lst = new List<CustomItem>();
return Json(lst.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
///cs html file
#(Html.Kendo().Grid<CustomItem>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.No).Width("15%");
columns.Bound(o => o.ShortDesc).Width("15%");
columns.Bound(o => o.Category).Width("6%");
})
.Sortable()
.Pageable(p=>p.Refresh(true))
.Filterable()
.Scrollable()
.Editable(edit => edit.DisplayDeleteConfirmation("Are You Sure To Delete This ").Mode(GridEditMode.PopUp))
.ColumnMenu(col=>col.Sortable(false))
.Groupable()
.ToolBar(toolbar => toolbar.Create())
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
//.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(6)
.Read(read => read.Action("GetItemsHome", "det"))
.Model(model => {
model.Id(p => p.ID);
})
.Create(update => update.Action("EditingInline_Create", "det"))
// .Read(read => read.Action("EditingInline_Read", "Default1"))
.Update(update => update.Action("EditingInline_Update", "det"))
.Destroy(update => update.Action("EditingInline_Destroy", "det"))
)
)
the order in which the JS is loaded
Any ideas ?
Thanks
Your action GetItemsHome([DataSourceRequest] DataSourceRequest request , int page) requires page (non-null value) to be passed. You have 3 options:
Delete this argument (this makes sense since request contains everything you want)
Supply it like: .Read(read => read.Action("GetItemsHome", "det", new { page = 10}))
Make it nullable like: int? page
EDIT: After following any of above, return some data from controller action (I am creating some arbitrary data, you may return it from DB instead) to fill up your grid. Something like:
public ActionResult GetItemsHome([DataSourceRequest] DataSourceRequest request , int? page)
{
//List<CustomItem> lst = new List<CustomItem>();
// Dummy data
var data = new [] { new CustomItem(){ No = 1, ShortDesc = "xyz", Category = "abc"},
new CustomItem(){ No = 2, ShortDesc = "xyz", Category = "abc"} };
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
If your controller and action names are spelled correctly in view, above code should work.
Some possibilities, if your function is not being called:
If your ActionResult Index() function is doing some other operations instead of simply return View() and exiting, it's possible your GetItemsHome() function may not be called - I had this issue once.
Try just naming the function "Read" instead of "GetItemsHome".
Does your controller have any other functions (i.e. Update, Destroy)? I would comment them out, in case there are syntax issues in them that are causing the issue.
"det", I hope, is the name of your controller.
Why pass in the extra page parameter at all? Try it without it, and use a public variable in your model to hold that value.

How to create Ajax-support Paging Nested Grid in Telerik MVC?

I try to create a Ajax-support Paging Nested Grid in Telerik MVC Extension. I have rendered the Nested Grid in browse, can expand row Genre to show the related Albums filtered by GenreId, but when i use Ajax for this nested Grid, it don't work in grid paging. I have upload my project and post some code about my View and Controller.
When i don't use ajax, the gird can work properly but it cannot expand correctly when browse is reloaded, how can i maintain the state of row which had expanded?
I'm gratiful for any help.
My Project:
http://share.vnn.vn/dl.php/11718146
My View:
#{
ViewBag.Title = "Home Page";
Layout = #"~\Views\Shared\_Layout.cshtml";
}
#( Html.Telerik().Grid<MvcMusicCodeFirsr.Models.Genre>(#Model)
.Name("personGrid")
.DataKeys(keys => keys.Add(k => k.GenreId))
.DataBinding(d => d.Ajax().Update( "_Update", "Home" )
)
// .Editable(editing => editing.Mode(GridEditMode.PopUp))
.Columns(c =>
{
c.Bound(m => m.Name).Width(150);
c.Bound(m => m.Description).Width(150);
//c.Bound(m => m.Birthdate);
c.Command(commands =>
{
commands.Edit();
}).Width(80);
})
.DetailView(detailView =>
detailView.Template(
#<text>
#(Html.Telerik().Grid<MvcMusicCodeFirsr.Models.Album>(item.Albums)
.Name("Albums_" + item.GenreId)
.DataBinding(d => d.Ajax())
.Columns(columns =>
{
columns.Bound(o => o.Title).Width(101);
columns.Bound(o => o.Price).Width(140);
})
.Pageable()
.Sortable()
.Filterable()
)
</text>
)
.ClientTemplate(
Html.Telerik().Grid<MvcMusicCodeFirsr.Models.Album>()
.Name("Albums_<#=GenreId#>")
.DataBinding(d => d.Ajax())
.Footer(false)
.ClientEvents(events => events.OnDataBinding("detailGrid_dataBinding"))
.ToHtmlString()
))
.Sortable()
.Pageable()
)
)
<script type="text/javascript">
function detailGrid_dataBinding(e) {
var grid = $(this).data("tGrid"),
masterRow = $(this).closest("tr.t-detail-row").prev(),
dataItem = $("#Grid").data("tGrid").dataItem(masterRow);
grid.dataBind(dataItem.Albums);
e.preventDefault();
}
</script>
My Controller:
MusicStoreEntities db = new MusicStoreEntities();
public ActionResult Index()
{
return View(db.Genres.ToList());
}
[GridAction]
public ActionResult _Select()
{
return View(new GridModel ( db.Genres.ToList()));
}
[GridAction]
public ActionResult _Update()
{
return View(new GridModel { Data = db.Genres.ToList() });
}
Here is an example showing ajax pading for the nested grid: http://demos.telerik.com/aspnet-mvc/grid/hierarchyajax

Ajax Binding Telerik MVC Grid with DetailView in one call

I have the following markup.
#(Html.Telerik().Grid(Model)
.Name("Grid")
.DataKeys(keys => keys.Add(key => key.Id))
.Columns(columns =>
{
columns.Bound(c => c.FullNameWithEmail).ClientTemplate("<#= FullNameWithEmail #>").Title("Name and Email").Width(230);
columns.Bound(c => c.Notes);
})
.ClientEvents(events => events.OnRowDataBound("grid_onRowDataBound"))
.DetailView(checkInAppGridDetails => checkInAppGridDetails.ClientTemplate("<# if (RelatedCount > 0) { #>" +
Html.Telerik().Grid<ViewModel>()
.Name("GridDetails_<#= Id #>")
.Footer(false)
.Columns(columns =>
{
columns.Bound(c => c.FullNameWithEmail).ClientTemplate("<#= FullNameWithEmail #>").Title("Name and Email").Width(225);
columns.Bound(c => c.Notes);
columns.Bound(c => c.Actions).ClientTemplate("<#= Actions #>").Width(150);
})
.ClientEvents(events => events.OnRowDataBound("GridDetails_onRowDataBound"))
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("GetRelated", "Controller", new
{
id = #ViewBag.EventKey,
ticketId = "<#= Id #>"
}))
.ToHtmlString() +
"<# } #>"
))
)
What i have here is that i am binding the main grid with Ajax call, and once rows got bound the details view gets bound with the DataBinding ajax call.
I already have in the Model a collection for the related records i wanted to show in the DetailView, i don't want the extra call to the server.
here is an example of the ViewModel
public class ViewModel
{
public string FirstProperty {get; set;}
.
.
.
public IEnumurable<ViewModel> RelatedRecords { get; set; }
}
Any idea how to bind the whole Grid with the DetailView with only single Ajax request?
Just used telerik support example to fix this, and it worked very well.Telerik Post

Telerik.Web.Mvc grid. In the .DetailView not calling the Ajax method

I am using free Telerik.Web.Mvc grid and following this example: http://demos.telerik.com/aspnet-mvc/grid/hierarchyajax
My Issue:
I am populating the grid with search results after user input some data and submit with a search button
In the DetailView() method I reference my 'SearchQuote_QuotesForHierarchyAjax' method, which is in defined in my Controller when DetailView executes data should be fetched, but this controller action does not execute for me.
If i load the grid first time page loads it execute. but not when the grid is loaded in a search button click
The Code in my project:
My SearchQuote.aspx View looks like this
<%= Html.Telerik().Grid(Model.QuoteSummaryList)
.Name("SearchQuoteGrid")
.Columns(columns =>
{
columns.Bound(q => q.QuoteId).Title("Quote #").Width(50);
columns.Bound(q => q.AxiomId).Title("Axiom Id").Width(180);
})
.ClientEvents(events => events.OnRowDataBound("quotes_onRowDataBound"))
.DetailView(details => details.ClientTemplate(
Html.Telerik().Grid(Model.QuoteSubSummaryList)
.Name("Quotes_<#= QuoteId #>")
.Columns(columns =>
{
columns.Bound(o => o.PositionCode).Width(101);
columns.Bound(o => o.Group).Width(140);
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("SearchQuote_QuotesForHierarchyAjax", "SearchQuote", new
{quoteid ="<#= QuoteId #>"}))
.Pageable()
.Sortable()
.Filterable()
.ToHtmlString()
))
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("SearchQuote_Select", "SearchQuote"))
.Sortable()
.Pageable(p => p.PageSize(3))
%>
<script type="text/javascript">
function expandFirstRow(grid, row) {
if (grid.$rows().index(row) == 0) {
grid.expandRow(row);
}
}
function quotes_onRowDataBound(e) {
var grid = $(this).data('tGrid');
expandFirstRow(grid, e.row);
}
</script>
And SearchQuoteController has this code.
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult SearchQuote_QuotesForHierarchyAjax(int quoteid)
{
List<QuoteLineSummaryDM> sublist = new List<QuoteLineSummaryDM>();
QuoteLineSummaryDM a = new QuoteLineSummaryDM();
a.PositionCode = "50";
a.Group = "1";
sublist.Add(a);
QuoteLineSummaryDM b = new QuoteLineSummaryDM();
b.PositionCode = "40";
b.Group = "2";
sublist.Add(b);
var qrows = (from r in sublist
select r).AsQueryable();
return View(new GridModel(qrows));
}
What am I missing? My version is even simpler than the demo. Any ideas?
Thanks.
I found another grid that does what I want to do. It's called jqGrid

Resources