New to Telerik UI for ASP.NET Core? Download free 30-day trial

Defining Custom HtmlHelpers

Environment

Product Telerik UI for ASP.NET Core
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 Core component?

Solution

This example shows how to define a custom HtmlHelper named MyGrid by extending the Grid component.

  1. Define a static Extension Method to extend the Grid configuration.
  2. Add the desired options to the method and return the extended type.
  3. 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 IHtmlHelper<dynamic> 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. You can use this as a starting point to configure the same behavior in an ASP.NET Core project.

More ASP.NET Core Grid Resources

See Also

In this article