Defining Custom HtmlHelpers
Environment
Product | Telerik UI for ASP.NET MVC |
Product Version | Created with version 2024.4.1112 |
Description
How can I define a custom HtmlHelper that accepts additional configuration options by extending an arbitrary Telerik UI for ASP.NET MVC component?
Solution
This example shows how to define a custom HtmlHelper named MyGrid by extending the Grid component.
- Define a static
Extension Method
to extend the Grid configuration. - Add the desired options to the method and return the extended type.
- From there, reference the extension method within the page where the component will be utilized.
namespace Telerik.Examples.Mvc.Areas.DefineCustomHtmlHelper.Helpers
{
public static class MyGridHelper
{
public static Kendo.Mvc.UI.Fluent.GridBuilder<T> MyGrid<T>(this HtmlHelper helper, string name)
where T : class
{
return helper.Kendo().Grid<T>()
.Name(name)
.Groupable()
.Sortable()
.Scrollable()
.Filterable()
.Pageable();
}
}
}
@using Telerik.Examples.Mvc.Areas.DefineCustomHtmlHelper.Helpers
@(Html.MyGrid<Telerik.Examples.Mvc.Areas.DefineCustomHtmlHelper.Models.OrderViewModel>("Grid1")
.Columns(columns =>
{
columns.Bound(p => p.OrderID).Filterable(false);
columns.Bound(p => p.Freight);
columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
columns.Bound(p => p.ShipName);
columns.Bound(p => p.ShipCity);
})
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "Home"))
)
)
For a runnable example, refer to the ASP.NET MVC application in the UI for ASP.NET MVC Examples repository.