Kendo Grid - Detail Template - DataSource Read is not firing the controller action - asp.net-mvc

App type: ASP.NET MVC with Kendo framework
Problem Encountered: The detail template is not firing the controller action method. Please find the attached screenshot also. I checked it under the firebug window also, there is no ajax call to the controller action method "PublishedImportFiles_Read". This is making me crazy and annoying. No error is thrown or shown for this anomaly. I guess i am missing something very small.
Please help.
MVC - View Code
<div class="gapLeft gapBelow20" style="width:70%;">
#(Html.Kendo().Grid<ViewModels.PublishedImportViewModel>()
.Name("GridImport")
.Columns(columns =>
{
columns.Bound(p => p.TemplateGroup).Title("Template Group").Width("120px");
columns.Bound(p => p.TaxYear).Title("Tax Year").Width("70px");
columns.Bound(p => p.FileDescription).Title("Description").Width("200px");
columns.Bound(p => p.DatePublished).Title("Published Date").Format("{0:MM/dd/yyyy}").Width("100px");
columns.Bound(p => p.PublishedBy).Title("Published By").Width("100px");
})
.Scrollable()
.ClientDetailTemplateId("tplGridImport")
.Events(et => et.DataBound(fnCall.Replace("functionName", "gridImpDataBound")))
.Events(et => et.DetailInit(fnCall.Replace("functionName", "gridImpChildInit")))
.HtmlAttributes(new { style = "height:300px;" })
.DataSource(ds => ds.Ajax().ServerOperation(false)
.Read(read => { read.Action("PublishedImport_Read", "Import"); })
.Model(m => { m.Id(p => p.TemplateGroupID); })
)
)
</div>
<script id="tplGridImport" type="text/kendo-tmpl">
#(Html.Kendo().Grid<ViewModels.PublishedImportViewModel>()
.Name("GridImport_#=TemplateGroupID#")
.Columns(columns =>
{
columns.Bound(c => c.TemplateGroup).Title("Template Group").Width("120px");
columns.Bound(c => c.TaxYear).Title("Tax Year").Width("70px");
})
.DataSource(dsx => dsx.Ajax()
.Read(rd => { rd.Action("PublishedImportFiles_Read", "Import"); })
)
.ToClientTemplate()
)
</script>
Import Controller ActionResult Method:
[OutputCache(Duration = 0)]
public ActionResult PublishedImportFiles_Read([DataSourceRequest] DataSourceRequest request)
{
int groupID = 5;
IEnumerable<PublishedImportViewModel> pubVM = Enumerable.Empty<PublishedImportViewModel>();
var pubRecords = base.ScenarioMangtService.GetPublishedImportFilesByTemplateGroup(ClientID, SelectedYear, groupID);
pubVM = pubRecords.Select(s => new PublishedImportViewModel
{
ImportFileJobID = s.ImportFileJobID,
TemplateGroupID = s.TemplateGroupID,
TemplateGroup = s.TemplateGroup,
FileName = s.FileName,
FileDescription = s.FileDescription,
TaxYear = SelectedYear,
DatePublished = s.DatePublished,
PublishedBy = s.PublishedBy
});
return Json(pubVM.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

There was nothing wrong with the KendoGrid code. Strangely, there was a javascript error in another js file. And for some weird reason, it was breaking the binding of the detail template grid.
So when i commented the other broken code in another file, this grid starts working automatically.

Related

DatasourceRequest always return null when Kendo grid is in PopUp

I am trying to open kendo grid in popup on clicking of link. Kendo grid Opens in popup perfectly, but filtering and sorting functionality is not working. I am using server side Operation. When I sort particular column In controller side in DatasourceRequest I always gets value as null.
Any help is highly appreciated..
<div class="panel-body" id="countryImageData">
#(Html.Kendo().Grid(Model.GlobalInventoryImages)
.Name("InventoryCountryImageDetailsGrid")
.Columns(columns =>
{
columns.Bound(p => p.SmartInventoryID).Hidden().Title("SPC #").HtmlAttributes(new { #id = "CountrySmartInventory_Grid" });
columns.Bound(p => p.SubwayProductCode).Width(50).Title("SPC #").HtmlAttributes(new { #id = "CountrySubwayProductCode_Grid" });
columns.Bound(p => p.GlobalCaseImageName).Width(100).Title("Case Images").HtmlAttributes(new { #id = "GlobalCaseGraphicName_Grid" }).ClientTemplate(" #=GlobalCaseImageName# ");
columns.Bound(p => p.GlobalInnerImageName).Width(100).Title("Inner Images ").HtmlAttributes(new { #id = "GlobalInnerImageName_Grid" }).ClientTemplate(" #=GlobalInnerImageName# ");
columns.Bound(p => p.CountryNames).Width(100).Title("Country").HtmlAttributes(new { #id = "CountryNames_Grid" });
})
.Pageable(pager => pager.PageSizes(new int[] { 25, 50, 75, 100 }).Input(true))
.Sortable(e => e.AllowUnsort(true).SortMode(GridSortMode.MultipleColumn))
.Scrollable()
.ColumnMenu()
.NoRecords("No Records")
.Selectable(e => e.Mode(GridSelectionMode.Multiple))
.Filterable()
.ColumnResizeHandleWidth(10)
.ColumnResizeHandleWidth(10)
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.HtmlAttributes(new { #class = "custom-kendo-grid custom-kendo-grid-inv" })
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(true)
.PageSize(25)
.Read(read => read.Action("InventoryImage_Read", "Inventory").Data("function onCountryAdditonalData(){ return {subwayProductCode: $('#SubwayProductCode').val()};}"))
)
)
</div>
With MVC you have to add the following in your dataSource:
type: 'aspnetmvc-ajax'
for the filter and sort not to be null. Also, your Action method in your MVC Controller must have parameters set up like so:
public async Task<ActionResult> InventoryImage_Read([DataSourceRequest] DataSourceRequest )
You didn't post your MVC Controller Action so I wasn't sure if you had that part set up correctly. I hope this helps.

excel export issue in telerik mvc grid

i have a telerik mvc grid where the excel export function fails because the read action of the grid has extra parameters.
the read action looks like this :
public ActionResult My_ReadAction([DataSourceRequest]DataSourceRequest request, string startDate, string endDate)
{
DateTime _startDate, _endDate;
_startDate = DateTime.ParseExact(startDate, "yyyyMMdd", CultureInfo.InvariantCulture);
_endDate = DateTime.ParseExact(endDate, "yyyyMMdd", CultureInfo.InvariantCulture);
IQueryable<CM_DISTRIBUTION_SCHEDULE> cm_distribution_schedule = db.CM_DISTRIBUTION_SCHEDULE
.Where(x => x.REF_DATE >= _startDate && x.REF_DATE <= _endDate);
DataSourceResult result = cm_distribution_schedule.ToDataSourceResult(request, cM_DISTRIBUTION_SCHEDULE => new
{
RECORD_ID = cM_DISTRIBUTION_SCHEDULE.RECORD_ID,
REF_DATE = cM_DISTRIBUTION_SCHEDULE.REF_DATE,
BRANCH_ID = cM_DISTRIBUTION_SCHEDULE.BRANCH_ID,
CURRENCY = cM_DISTRIBUTION_SCHEDULE.CURRENCY,
FORECAST_AMOUNT = cM_DISTRIBUTION_SCHEDULE.FORECAST_AMOUNT
});
return Json(result);
}
and the grid :
#(Html.Kendo().Grid<MyClass.MyViewModel>().Name("BranchFcast").AutoBind(false) .HtmlAttributes(new { style = "height: 100%; border: 0;" })
.Columns(columns =>
{
columns.Bound(c => c.REF_DATE).Title("Forecast Date").Format("{0:d}").Width(130);
columns.ForeignKey(f => f.BRANCH_ID, (System.Collections.IEnumerable)ViewData["branches"], "BranchId", "BranchName").Title("Branch").Width(200);
columns.ForeignKey(f => f.CURRENCY, (System.Collections.IEnumerable)ViewData["currencies"], "CurrencyId", "CurrencyName").Title("Currency").Width(150);
columns.Bound(c => c.FORECAST_AMOUNT).Title("Forecast Amount").Format("{0:c}").Width(150);
columns.Bound(c => c.TXN_AMOUNT).Title("Amended Forecast").Width(150);
})
.ToolBar(toolbar => {
toolbar.Excel();
}).Excel(excel => excel.FileName("DistSchedule.xlsx").Filterable(true).ProxyURL(Url.Action("Excel_Export_Save", "DistSched")).AllPages(true))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model =>
{
model.Id(p => p.RECORD_ID);
model.Field(p => p.RECORD_ID).Editable(false);
model.Field(p=> p.REF_DATE).DefaultValue(DateTime.Today);
}
)
.Sort(s => s.Add(f => f.REF_DATE).Descending()).Read(read => read.Action("My_ReadAction", "Controller")))
)
So when the export button is clicked, it fires My_ReadAction but doesnt pass the parameter, causing the controller action to fail.
Is there a way to modify the export events such that i can pass the parameters. Any other workaround is welcome.
Add a .Data() fluent method to the Ajax DataSource settngs and implement a JavaScript function that will return a plain object with the two dates. This is the recommended way to pass custom parameters to the Grid's Read action method.
http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/binding/ajax-binding#pass-additional-data-to-action-methods

Kendo Grid Paging doesn't work in Asp.Net MVC

I am trying to bind a Kendo Grid in Asp.Net MVC but the paging doesn't work. The PageSize and the Total records are correct, the problem is that it isn't possible to navigate to the next page. All the buttons are displayed but they are disabled.
The view's code is:
<% Html.Kendo().Grid(Model)
.Name("PartListGrid")
.Columns(columns =>
{
columns.Bound(p => p.Id).Title("Id").Visible (false);
columns.Bound(p => p.Quantity).Title("Quantity")).Width(130);
columns.Bound(p => p.PartNumber).Title("Part Number").Width(130);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p=>p.Id))
.PageSize(5)
.ServerOperation(false)
)
.Pageable()
.Render();
%>
The Controller's code :
public ActionResult GetPartListInfo(string id)
{
List<PartListViewModel> partList = new List<PartListViewModel>();
XrmServiceContext xrmServiceContext = new XrmServiceContext();
f1_workorder workOrder = xrmServiceContext.f1_workorderSet.Where(i => i.Id == new Guid(workOrderId)).FirstOrDefault();
PartListViewModel partViewModel = null;
foreach (f1_workorderproduct workorderproduct in xrmServiceContext.f1_workorderproductSet.Where(i => i.f1_WorkOrder.Id == workOrder.Id).ToList())
{
Product product = xrmServiceContext.ProductSet.Where(j => j.Id == workorderproduct.f1_Product.Id).FirstOrDefault();
partViewModel = new PartListViewModel();
partViewModel.Id = workorderproduct.f1_Product.Id.ToString();
partViewModel.Quantity = workorderproduct.f1_EstimateQuantity.GetValueOrDefault(0);
partViewModel.PartNumber = workorderproduct.f1_name;
partList.Add(partViewModel);
}
return View("PartList",partList);
}
Any advice is appreciated!
Thank you very much for your help!
Mimi
I bet you have to throw in a data source read configuration so that the dataset can fetch the data on paging when needed.
.DataSource(dataSource => dataSource
...
.Read(read => read.Action("YourAction", "YourController))
...

Kendo MVC Grid Within a Window DataSource Read

I'm trying to populate a kendo grid within a kendo window in MVC and am unable to find what is wrong. The window is created, and the grid is created within the window... however the DataSource's Read method is never called.
Window:
#{
Html.Kendo().Window()
.Name("DListing")
.Title("Listing")
.Draggable()
.Resizable()
.Width(1000)
.Height(500)
.Visible(true)
.Modal(true)
.Actions(actions => actions
.Maximize()
.Close())
.LoadContentFrom("Dispatch", "Listing", new { Number = #ViewBag.Number })
.Render();}
The Dispatch method in the Listing controller returns back a partial view that contains the grid.
Grid:
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Events(events => events.Change("onChange"))
.HtmlAttributes(new { style = "height:400px;" })
.Columns(columns =>
{
columns.Bound(p => p.Number);
columns.Bound(p => p.DateTime).Format("{0:MM/dd/yyyy hh:mm tt}");
columns.Bound(p => p.Location);
columns.Bound(p => p.Name);
columns.Bound(p => p.Elapsed_Hours);
})
.Groupable()
.Pageable(pageable => pageable
.Numeric(false)
.Input(true)
.PageSizes(new[] { 5, 10, 25 }))
.Sortable()
.Scrollable(scrollable => scrollable
.Virtual(true))
.Filterable()
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Multiple))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(13)
.Sort(sort => { sort.Add(p => p.DateTime).Descending(); })
.Model(model => { model.Id(p => p.Number); })
.Read(read => read.Action("Listing_Read", "Listing", new { Number = #ViewBag.Number })))
)
Listing_Read Method:
public ActionResult Listing_Read([DataSourceRequest] DataSourceRequest request, int Number)
{
return Json(GetListing(branchNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
Also, it should be noted that I went through and verified that the viewbag data is available for both the window and later on in the grid.
For a little more back info, I initially had the grid on it's own page and it was able to call the read method and populated with the data with no issues. After moving it to populate in the window is when this became a problem.
Monitoring the http requests, the grid never attempts to call the read method (so the request isn't failing). I tried manually refreshing the datasource after the window has loaded thinking that might force the call, but that doesn't call the read method either.
I've been scratching my head on this one for a few hours now trying different things, hoping someone can spot what the problem is :)
Here's what worked for me:
1) View (~/Views/Home/Index.cshtml)
#(Html.Kendo().Window()
.Name("myWindow")
.Title("Title")
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
//.Content(Html.Partial("gridCat").ToHtmlString())
.LoadContentFrom("Load_gridCat", "Home")
)
2) Partial View (~/Views/Shared/gridCat.cshtml)
#(Html.Kendo().Grid<TelerikMvcApp1.Models.Category>()
.Name("CategoriesGrid")
.Columns(columns =>
{
columns.Bound(c => c.CategoryID).Title("Category").Width("10%");
columns.Bound(c => c.CategoryName);
columns.Bound(c => c.Description);
})
.Filterable()
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.CategoryID))
.Read(r => r.Action("Categories_Read", "Home"))
)
.HtmlAttributes(new { style = "height:250px" })
)
3) Controller (~/Controllers/HomeController.cs)
public ActionResult Load_gridCat()
{
return PartialView("gridCat");
}
public ActionResult Categories_Read([DataSourceRequest]DataSourceRequest request)
{
using (var ctx = new NWindContext())
{
IQueryable<Category> categories = ctx.Categories;
DataSourceResult result = categories.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
}

Kendo UI Grid Batch Edit After Saving Changes - Microsoft JScript runtime error: Expected ';'

I am using Kendo UI ASP.Net MVC - Grid - Batch Edit,
Upon clicking 'Save'. Data gets saved in database successfully.
But "kendo.web.min.js" is throwing error "Microsoft JScript runtime error: Expected ';'"
#model IEnumerable<EOL.RecOil.Models.ControllerActionViewModel>
#using Kendo.Mvc.UI;
<div>
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ID).Visible(false);
columns.Bound(p => p.ControllerName);
columns.Bound(p => p.ActionName);
columns.Bound(p => p.HasAccess);
columns.Bound(p => p.UserAccessID).Visible(false);
columns.Bound(p => p.ControllerID).Visible(false);
columns.Bound(p => p.ActionID).Visible(false);
})
.Filterable()
.Groupable()
.Editable(editable => editable.Mode(GridEditMode.InCell))
.ToolBar(toolBar => { toolBar.Save(); })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Events(events => events.Error("error"))
.Update(update => update.Action("Edit","ControllerActions"))
.ServerOperation(false)
.Model(x =>
{
x.Id(p => p.ID);
x.Field(p => p.ControllerName).Editable(false);
x.Field(p => p.ActionName).Editable(false);
x.Field(p => p.HasAccess).Editable(true);
})
)
)
</div>
[HttpPost]
public ActionResult Edit([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable<ControllerActionViewModel> controllerActionViewModel)
{
try
{
if (controllerActionViewModel != null && ModelState.IsValid)
{
foreach (var item in controllerActionViewModel)
{
db.Database.ExecuteSqlCommand("SaveUserAccess #UserID,#ControllerID,#ActionID,#UserAccessID,#HasAccess",
new SqlParameter("UserID", item.UserID),
new SqlParameter("ControllerID", item.ControllerID),
new SqlParameter("ActionID", item.ActionID),
new SqlParameter("UserAccessID", item.UserAccessID),
new SqlParameter("HasAccess", item.HasAccess)
);
}
}
}
catch (Exception ex)
{
Helper.SaveError(ex.InnerException.InnerException.Message, "ControllerActions", "Edit");
ModelState.AddModelError(string.Empty, ex.InnerException.InnerException.Message);
}
return Json(new[] { controllerActionViewModel }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
}
I think I may have discovered the answer to this problem, having wrestled with it for a good part of today.
My code looked very similar to yours. The return value of my action method looked like this:
return Json(new[] { viewmodel }.ToDataSourceResult(request, ModelState));
This gave me the exact javascript error you describe. After trying many things, I eventually compared the code to another method that was working fine and so I adjusted it slightly to this:
return Json(viewmodel.ToDataSourceResult(request, ModelState));
This is now working and my MVC application is no longer throwing the javascript error.
I hope this helps you #Jignesh.

Resources