I have a kendo grid setup like this
#(Html.Kendo().Grid(Model)
.Name("projects")
.Columns(columns =>
{
columns.Bound(c => c.ID).Width(90);
columns.Bound(c => c.Name).Width(300);
columns.Bound(c => c.Description);
columns.Bound(c => c.ProjectCode);
columns.Template(c => "").ClientTemplate(Html.ActionLink("Tasks", "TasksList", "Task", new { projectId = "#=ID#" }, new { #class = "k-button k-button-medium-grid" }).ToHtmlString()).Width(65);
})
)
This set up with the Client Template (for the last column) was working fine until I updated to the new version of Kendo (2014.3.1119)
Now i get an error on the page "Uncaught TypeError: Cannot read property 'context' of null".
Has anyone else bumped into this problem? Did the syntax change and now setting up the client template like this no longer works?
Thanks!
You should not use template and clientTemplate methods to the same column. If you are using field id just bind second column to this field:
#(Html.Kendo().Grid(Model)
.Name("projects")
.Columns(columns =>
{
columns.Bound(c => c.ID).Width(90);
columns.Bound(c => c.Name).Width(300);
columns.Bound(c => c.Description);
columns.Bound(c => c.ProjectCode);
columns.Bound(c => c.ID).ClientTemplate(Html.ActionLink("Tasks", "TasksList", "Task", new { projectId = "#=ID#" }, new { #class = "k-button k-button-medium-grid" }).ToHtmlString()).Width(65);
})
)
You can read more about Kendo MVC column templates in Kendo Grid FAQ.
Related
i'm new to kendo UI and currently learning about custom editor.
My Problem is i managed to get my editor template working in edit mode and populate the data just fine, but somehow it won't save the value to the display grid
I Retreive all my data from API.
UPDATE:
i've managed to properly save the value from the custom editor template to the controller and it works just fine, but using clientTemplate won't display the correct value from what i select in the dropdown, and only show a string
DropDown Only Display A String
my setup code is like this
#( Html.Kendo().Grid<SalesOrderDetailVM>()
.Name("list-detail")
.Columns(columns =>
{
columns.Bound(c => c.Product).ClientTemplate("\\#=Product.ProductId\\#").Title("Products");
columns.Bound(c => c.Quantity);
columns.Bound(c => c.UnitPrice);
})
.Editable(GridEditMode.InCell)
.ToolBar(tool =>
{
tool.Create();
tool.Save();
}
)
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Batch(true)
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.Product);
})
.Create(act => act.Action("DetailCell_Create","SalesOrder"))
)
)
DDLProduct.cshtml:
#model AAF.WEB.MVC.ViewModels.ProductVM
#(
Html.Kendo().DropDownListFor(m => m)
.DataValueField("ProductId")
.DataTextField("ProductName")
.OptionLabel("Select Product")
.BindTo((System.Collections.IEnumerable)ViewData["products"])
)
Edit Mode
DisplayMode / Out of Product Edit Mode
Use template method to acheive dropdown with kendo grid.
GridForeignKey.cshtml - it should placed in shared folder or EditorTemplates
#model object
#(
Html.Kendo().DropDownListFor(m => m)
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
)
In your kendo grid please change like below
#( Html.Kendo().Grid<AAF.WEB.MVC.ViewModels.SalesOrderDetailVM>()
.Name("list-detail")
.Columns(columns =>
{
columns.Bound(c => c.Id)
columns.ForeignKey(c => c.ProductId, (System.Collections.IEnumerable)ViewData["Products"], "ProductId", "ProductName").Title("Products");
columns.Bound(c => c.Quantity);
columns.Bound(c => c.UnitPrice);
})
.Editable(GridEditMode.InCell)
.ToolBar(tool =>
{
tool.Create();
tool.Save();
}
)
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
You can set the products data to view data. using this method you can save the product id.
Thanks
Okay after i frustrated for many hours, finally found the solution
the solution is to add a defaultvalue to the passed model in the grid
.Model(model =>
{
model.Id(p => p.ProductId);
model.Field(p => p.Product).DefaultValue(
ViewData["defaultProduct"] as ProductVM
);
})
and pass the data from the controller
// Function that get data from API
ViewData["products"] = products;
ViewData["defaultProduct"] = products.First();
I am Migrating the app from MVC 5 to Core 2.0. We are facing issue with the grid client template as we are unable to use it when we use it along with the editable property. Following is the code.
#(Html.Kendo().Grid<PPVR>()
.Name("PPVRGird")
.Columns(columns =>
{
columns.Bound(e => e.Id).Hidden();
columns.Bound(c => c.Name);
columns.Bound(c => c.Quantity);
columns.Bound(c => c.Type);
columns.Bound("").ClientTemplate("<div style='text-align:center'><a href='javascript:void(0)' class='k-grid-edit custom-action-button'onclick='customGridEditClick(this)'><img src='/Content/edit.svg' width ='40' height='40'/><br/>Edit</a></div>").HeaderHtmlAttributes(new { #class = "custom-action-button" }).Title("Edit").Width(150);
columns.Bound("").ClientTemplate("<div style='text-align:center'><a href='javascript:void(0)' class='custom-action-button pull-center' onclick='deletePayPerViewRules(#=Id#)'><img src='/Content/trashed.svg' width='40' height='40' /><br />Delete</a></div>").HeaderHtmlAttributes(new { #class = "custom-action-button" }).Width(200);
})
.Pageable()
.HtmlAttributes(new { style = " text-align:left; font-family:lato; font-size:16px; " })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Read(read => read.Action("GetPPVR", "PPV"))
.Model(model =>
{
model.Id(u => u.Id);
model.Field(u => u.Type).Editable(false);
})
.Update(update => update.Action("UpdatePPVR", "PPV")))
.Editable(editable => editable.Mode(GridEditMode.InLine))
)
This brings the empty page. When I comment the line .Editable(editable => editable.Mode(GridEditMode.InLine)) page appears. It works well in MVC 5 but not in core 2.0.
Kindly suggest how can I achieve this.
UPDATE => This issue is coming only when I am using Inline option for editing when I use Pop Up then it works fine.
Okay after 2 days of waiting I got the response from Telerik Team.
A possible solution is to bind the desired columns to any field, and using the columns.editable configuration to prevent editing for these columns.
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/columns.editable
columns.Bound(p => p.Freight).ClientTemplate("Hi").HeaderHtmlAttributes(new { #class = "custom-action-button" }).Width(200).Editable("function(){return false;}");
columns.Bound(p => p.Freight).ClientTemplate("Bye").HeaderHtmlAttributes(new { #class = "custom-action-button" }).Title("Sample").Width(150).Editable("function(){return false;}");
Telerik Team Answer
It seems to be a workaround for me but it worked fine.
Hope this question saves someother people time as well.
I have a very wired problem.
My kendo grid pager controls are getting rendered twice after I updated kendo files.
Someone knows something about this. I'm using Kendo for ASP.NET MVC.Here you have an image of the grid
The second group of buttons are the ones that works. Buttons to the right and left of the pagination numbers are blocked.
#(Html.Kendo().Grid<Monibyte.Arquitectura.Presentacion.Transaccional.Dto.Tarjetas.PocMovimientosTarjeta>()
.Name("Grid")
.Filterable()
.Groupable()
.ColumnMenu()
.AutoBind(false)
.Events(e => e.DataBound("OndataBound"))
.Events(e => e.DataBinding("OnDataBinding"))
.Reorderable(reorderable => reorderable.Columns(true))
.Pageable(pager => pager.PageSizes(Html.DefaultPageSizes()))
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Sortable(sortable => sortable.AllowUnsort(true).SortMode(GridSortMode.MultipleColumn))
.Columns(columns =>
{
columns.Bound(p => p.IdMovimiento).Title("").Sortable(false).Filterable(false).Width(50)
.HtmlAttributes(new { #class = "detAdic_ListMov" }).IncludeInMenu(false)
.HeaderTemplate(Html.GridCheckAll()).ClientTemplate(Html.GridCheck() +
Html.GenericGridBtn("IncluirDetalleMovimiento", "ConsultaMovimientos", null,
altText: #RecEtiquetas.App_AgregarMovimiento,
jsparams: new
{
targetId = "detalleMovimiento",
dataFunc = "editarDataFunc",
callback = "editarCallback"
},
imageUrl: "imagenes/iconos/list(16).png",
authorizeFunc: "validaSegregar").ToHtmlString())
.HtmlAttributes(new { #class = "detAdic_ListMov", #title = #RecEtiquetas.App_AgregarMovimiento });
columns.Bound(p => p.NumTarjeta).Title(RecEtiquetas.Mod_NumTarjeta).Hidden(true).Width(50)
.ClientGroupHeaderTemplate("#= templateDescripcionTarjeta(value) #")
.HtmlAttributes(new { #title = #RecEtiquetas.Mod_NumTarjeta });
columns.Bound(p => p.NumReferencia).Title(RecEtiquetas.App_Referencia).Width(30)
.HtmlAttributes(new { #title = #RecEtiquetas.App_Referencia });
columns.Bound(p => p.FecMovimiento).Title(RecEtiquetas.App_FechaMovimiento).Width(40)
.ClientTemplate("#:$monibyte.formatDate(FecMovimiento)#")
.HtmlAttributes(new { #title = #RecEtiquetas.App_FechaMovimiento });
columns.Bound(p => p.FecTransaccion).Title(RecEtiquetas.App_FecConsumo).Hidden(true).Width(40)
.ClientTemplate("#:$monibyte.formatDate(FecTransaccion)#")
.HtmlAttributes(new { #title = #RecEtiquetas.App_FecConsumo });
columns.Bound(p => p.Descripcion).Title(RecEtiquetas.App_DescripcionMovimiento).Width(250)
.HtmlAttributes(new { #title = #RecEtiquetas.App_Descripcion });
columns.Bound(p => p.MonDebLocal).Title(Html.EtiquetasCompania("RecGlobalizacion", "App_DebitoMonedaLocal").ToString()).Width(40)
.ClientTemplate("#:SimboloMonedaLocal# #:$monibyte.formatNumber(MonDebLocal)#")
.ClientGroupFooterTemplate("#:templateMontoDebLocal(data)#")
.FooterHtmlAttributes(new { #class = "alinearDerecha" })
.HtmlAttributes(new { #class = "alinearDerecha monto-grid", #title = Html.EtiquetasCompania("RecGlobalizacion", "App_DebitoMonedaLocal") });
columns.Bound(p => p.MonCredLocal).Title(Html.EtiquetasCompania("RecGlobalizacion", "App_CreditoMonedaLocal").ToString()).Width(40)
.ClientTemplate("#:SimboloMonedaLocal# #:$monibyte.formatNumber(MonCredLocal)#")
.ClientGroupFooterTemplate("#:templateMontoCredLocal(data)#")
.FooterHtmlAttributes(new { #class = "alinearDerecha" })
.HtmlAttributes(new { #class = "alinearDerecha monto-grid", #title = Html.EtiquetasCompania("RecGlobalizacion", "App_CreditoMonedaLocal") });
columns.Bound(p => p.MonDebInter).Title(RecEtiquetas.App_DebitoDolares).Width(40)
.ClientTemplate("#:SimboloMonedaInter# #:$monibyte.formatNumber(MonDebInter)#")
.ClientGroupFooterTemplate("#:templateMontoDebInter(data)#")
.FooterHtmlAttributes(new { #class = "alinearDerecha" })
.HtmlAttributes(new { #class = "alinearDerecha monto-grid", #title = #RecEtiquetas.App_DebitoDolares });
columns.Bound(p => p.MonCredInter).Title(RecEtiquetas.App_CreditoDolares).Width(40)
.ClientTemplate("#:SimboloMonedaInter# #:$monibyte.formatNumber(MonCredInter)#")
.ClientGroupFooterTemplate("#:templateMontoCredInter(data)#")
.FooterHtmlAttributes(new { #class = "alinearDerecha" })
.HtmlAttributes(new { #class = "alinearDerecha monto-grid", #title = #RecEtiquetas.App_CreditoDolares });
columns.Bound(p => p.DescripcionMoneda).Title(RecEtiquetas.App_Moneda).Hidden(true).Width(40)
.ClientGroupHeaderTemplate(RecEtiquetas.App_TotalRegistros + " #=value# = #=count#")
.HtmlAttributes(new { #title = #RecEtiquetas.App_Moneda });
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(Html.DefaultPageSize())
.Sort(sort => sort.Add(p => p.FecMovimiento).Descending())
.Aggregates(aggregates =>
{
aggregates.Add(p => p.MonCredLocal).Sum();
aggregates.Add(p => p.MonDebLocal).Sum();
aggregates.Add(p => p.MonCredInter).Sum();
aggregates.Add(p => p.MonDebInter).Sum();
aggregates.Add(p => p.DescripcionMoneda).Count();
aggregates.Add(p => p.SimboloMonedaLocal).Min();
aggregates.Add(p => p.SimboloMonedaInter).Min();
})
.Group(groups => groups.Add(p => p.DescripcionMoneda))
.Read(read => read.Action("FiltrarMovimientos", "ConsultaMovimientos"))
))
I contacted Progress Telerik support and this is the answer they gave.
We had reports about such an issue recently. The customers who encountered it had updated UI for ASP.NET MVC to the latest version
but forgot to update the Kendo UI script and CSS files, or vice versa.
Could you double check if you updated both the DLL and the JS and CSS
files? To check the current Kendo UI scripts version in your page, you
can call:
console.log(kendo.version);
To check the DLL version, open the References folder in your project,
right-click Kendo.Mvc and select Properties.
The two versions have to match in order to have the widgets working
correctly
So check your dll and js/css versions match.
Had the same issue with kendo 2018.1.221. The issue was fixed when the jquery is loaded after the kendo javascript bundle
#Styles.Render("~/Content/kendo/2018.1.221/css")
#Scripts.Render("~/bundles/kendo/2018.1.221/kendoscripts")
//jquery needs to be loaded after kendo scripts
#Scripts.Render("~/bundles/jquery")
The reason why I was getting duplicate paging was because the Kendo.MVC.dll in the project did not match the Kendo css & scripts version used by the bundles.
Remove the Kendo.Mvc dll in your project and re-add from the local path. eg.
\Telerik UI for ASP.NET MVC R2 2018\wrappers\aspnetmvc\Binaries\Mvc4Kendo.Mvc.dll
(Same answer as Steven Anderson)
I have a grid with some editor templates. The grid can be edited InCell.
I want to change the edit inCell event so that it will edit the values on double click. Untill now I have done it like this :
$(table + " table").on("dblclick",
"tbody>tr>td",
function(e) {
var grid = $(table).data("kendoGrid");
grid.editCell($(this));
});
The problem that I have is that when I double click on the cell, the widget that I want for editing (Multiselect, DropdownList ...) is not rendered in the grid and looks like this :
Instead, it should look like this:
One of the editors looks like this :
#(Html.Kendo().DropDownList()
.Name("Responsible")
.DataTextField("ResponsibleName")
.DataValueField("ResponsibleId")
.BindTo((System.Collections.IEnumerable)ViewData["Responsible"])
);
The definition of the grid is :
#(Html.Kendo().Grid(Model.ActivitiesList)
.Name(Model.ActivitiesSection)
.ClientDetailTemplateId(Model.ActivitiesSection + "-description")
.Columns(columns =>
{
columns.Bound(c => c.ActivityId).Title(#Html.Kendo().CheckBox().Name("check-#=ActivitiesSection#").Checked(false).Enable(false).ToString()).ClientTemplate(#Html.Kendo().CheckBox().Name("check-#=ActivityId#").Checked(false).ToString()).Sortable(false);
columns.Bound(c => c.StatusColor).Title("").ClientTemplate("<i class='fa fa-circle' aria-hidden='true' style='font-size: smaller; color:#=StatusColor#;'></i>").Sortable(false);
columns.Bound(c => c.StatusDescription).Title("Status").ClientTemplate("#=StatusDescription#");
columns.Bound(c => c.Name).Title("Name").ClientTemplate("<p class='activity-name'>#=Name#</p>");
columns.Bound(c => c.Priority).Title("Priority").ClientTemplate("#=PriorityTemplate(Priority)#");
columns.Bound(c => c.Responsible).Title("Responsible").HtmlAttributes(new { #class = "templateCell" }).ClientTemplate("#=ResponsibleTemplate(Responsible)#");
columns.Bound(c => c.Team).Title("Team").ClientTemplate("Better solutions");
columns.Bound(c => c.GeographicResponsibility).Title("Geographic Resp").HtmlAttributes(new { #class = "templateCell" }).ClientTemplate("#=GeographicResponsibilityTemplate(GeographicResponsibility)#").EditorTemplateName("_GeographicalResponsibilityEditor");
columns.Bound(c => c.FunctionOrPracticeResponsible).Title("Function/Practice Resp").HtmlAttributes(new { #class = "templateCell" }).ClientTemplate("#=FunctionOrPracticeResponsibleTemplate(FunctionOrPracticeResponsible)#").EditorTemplateName("_FunctionResponsibleEditor");
columns.Bound(c => c.DueDate).Title("Due date").ClientTemplate("<p style='white-space: nowrap'>#= DueDate != null ? kendo.toString(kendo.parseDate(DueDate,'dd/MM/yyyy'), 'dd-MM-yyyy') : 'DD-MM-YY' #</p>").EditorTemplateName("_ActivityDueDateEditor");
columns.Bound(c => c.Starred).Title("<i class='fa fa-star' aria-hidden='true' style='color: #ededed; font-size:large;'></i>").ClientTemplate("<i class='fa fa-star' aria-hidden='true' style='color:\\#ededed;'></i>").Sortable(false);
columns.Bound(c => c.StatusDescription).Title("<i class='fa fa-file' aria-hidden='true' style='color: #ededed; font-size:large'></i>").ClientTemplate("<i class='fa fa-file' aria-hidden='true' style='color:\\#ededed;'></i>").Sortable(false);
columns.Bound(c => c.ActivityId).Title("").ClientTemplate("<input type='button' value='More Info' class='expanded-section' id='#= ActivityId #'/>").Sortable(false);
columns.Bound(c => c.ActivityId).Title("").ClientTemplate("<input type='hidden' class='js-activity-id' value='#= ActivityId #'").Sortable(false);
columns.Bound(c => c.KeyLaunchElementId).Hidden(true);
columns.Bound(c => c.ProcessMapId).Hidden(true);
columns.Bound(c => c.WorkstreamId).Hidden(true);
})
.DataSource(e => e.Ajax().ServerOperation(false).Sort(a => a.Add("Name").Ascending())
.Model(model =>
{
model.Id(act => act.ActivityId);
model.Field(act => act.Name);
model.Field(act => act.ActivityId).Editable(false);
model.Field(act => act.Priority).DefaultValue(new ActivityPriorityViewModel());
model.Field(act => act.StatusColor).Editable(false).DefaultValue("#00b0d3");
model.Field(act => act.StatusDescription).DefaultValue("New").Editable(false);
model.Field(act => act.Responsible).DefaultValue(new ActivityResponsibleViewModel());
model.Field(act => act.Team).Editable(false);
model.Field(act => act.GeographicResponsibility).DefaultValue(new GeographicalResponsibilityViewModel());
model.Field(act => act.FunctionOrPracticeResponsible).DefaultValue(new List<FunctionOrPracticeViewModel>());
model.Field(act => act.DueDate);
model.Field(act => act.Starred).Editable(false);
})
.Update(update => update.Action("UpdateActivity", "Activity"))
.AutoSync(true))
.Events(events => events.DetailExpand("detailExpand").Save("function(e) { this.dataSource.sync() }").DataBound("activityFilter.IsSorted"))
.Sortable(s => s.SortMode(GridSortMode.SingleColumn).AllowUnsort(false))
.Editable(edit => edit.Mode(GridEditMode.InCell))
)
Thank you!
At first create new editor and place it under directory: Views/Shared/EditorTemplates directory. I created "DropdownTest.cshtml" editor:
#using Kendo.Mvc.UI
#(
Html.Kendo().DropDownListFor(m => m)
.BindTo((System.Collections.IEnumerable)ViewData["Responsible"])
.DataValueField("ResponsibleId")
.DataTextField("ResponsibleName")
)
ViewData["Responsible"] is used to list all of positions while editing, so it must be initialized in view method:
public ActionResult Index()
{
ViewData["Responsible"] = new List<Responsible>()
{
new Responsible
{
ResponsibleId = 1,
ResponsibleName = "Test-A"
},
new Responsible
{
ResponsibleId = 2,
ResponsibleName = "Test-B"
}
};
return View();
}
A grid wrapper column definition (instead of bound - use foreign key):
columns.ForeignKey(p => p.Responsible.ResponsibleId, (System.Collections.IEnumerable)ViewData["Responsible"],
"ResponsibleId", "ResponsibleName").EditorTemplateName("DropdownTest");
EditorTemplateName("DropdownTest") is linked to editor from EditorTemplates directory.
I have a Kendo Grid which has a popup editable template,
If possible i would like to pass the model (the model of the row, or at least its Id) to the editable template
Grid
#(Html.Kendo().Grid<Client>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Name).Width(140);
columns.Bound(c => c.Status);
columns.Bound(c => c.ProcesingStyle);
columns.Bound(c => c.ArchiveDays);
columns.Command(command =>
{
command.Edit().Text(" ");
command.Destroy().Text(" "); ;
}).Width(90);
})
.ToolBar(toolbar => toolbar.Create().Text("New"))
.Editable(editable => editable
.Mode(GridEditMode.PopUp)
.TemplateName("Client").AdditionalViewData(new { Client = Model })
.Window(w => w.Title("Site")))
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Sortable()
.Selectable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Events(events => events.Change("onChange"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Get", "Clients"))
.Model(model => model.Id(p => p.Id))
.Create(update => update.Action("Create", "Clients"))
.Update(update => update.Action("Update", "Clients"))
.Destroy(update => update.Action("Destroy", "Clients"))
)
)
Template
#model Client
#(Html.Kendo().ComboBoxFor(m => m.Plan)
.DataTextField("Name")
.DataValueField("Id")
.Placeholder("Select Plan...")
.HtmlAttributes(new { style = "width:300px" })
.Filter(FilterType.Contains)
.MinLength(3)
.DataSource(source =>
source.Read(read =>
read.Action("GetPlans", "Plans",new {ClientId = Model.Id}))))
Everything works fine except i need to use the Id of the row/model inside the template, in particular , i need the to pass the model.Id (which is the id of the model of the row), to the action on the Combobox in the template, so i can filter the data correctly
This is the offending line in the grid,
.TemplateName("Client").AdditionalViewData(new { Client = Model })
The result is the Model inside the template is always null, im not sure how to pass the data i need to the template
Is there anyway i can do this, or should i be looking at a different approach?
The way I got around this was to put a JavaScript function in the original view as seen below:
function getClientId() {
var row = $(event.srcElement).closest("tr");
var grid = $(event.srcElement).closest("[data-role=grid]").data("kendoGrid");
var dataItem = grid.dataItem(row);
if (dataItem)
return { clientId: dataItem.Id }
else
return { clientId: null }
}
And reference it from my editor template:
.DataSource(source => source.Read(read => read.Action("GetPlans", "Plans").Data("getClientId"))))
Note : I'm pretty sure you cant run JavaScript from a EditorTemplate so it needed to be housed in the original view.
I know this is a really old question, but for those who are wondering why this doesn't work:
.TemplateName("Client").AdditionalViewData(new { Client = Model })
This code doesn't work because the only data you can pass through this method is static data. You can pass specific strings or numbers, like "Hello World", and that would work fine. For dynamic data with kendo, I've learned that it really depends on the situation, and your solution here works well.