Using Kendo UI in HTML helpers or Extensions

Creating HTML helpers with Kendo UI

If repeating similar code in multiple views then it may be worth while to split out the common code into HTML helpers.

Add a new file into the web projects App_code directory

Then fill it with the helpers you require. Syntax is just like using the helper on your web page.

@using Kendo.Mvc.UI;
@using System.Web.Mvc;
@using System.Web.Mvc.Html;

@helper CBGridToolButtons(WebViewPage page) {
<div class="CBholderitem">  
  .HtmlAttributes(new { type = "button", style = "width: 50px" })
  .Events(ev => ev.Click("CBgrid.SelectAll")))
@(page.Html.Kendo().Tooltip().For("#ButtonGridSelectAll").Position(TooltipPosition.Top).Content("Select All"))

  .HtmlAttributes(new { type = "button", style = "width: 50px" })
  .Events(ev => ev.Click("CBgrid.ClearAll")))
@(page.Html.Kendo().Tooltip().For("#ButtonGridClearAll").Position(TooltipPosition.Top).Content("Clear Selection"))

  .HtmlAttributes(new { type = "button", style = "width: 50px" })
  .Events(ev => ev.Click("CBgrid.ClearFilters")))
@(page.Html.Kendo().Tooltip().For("#ButtonGridClearFilters").Position(TooltipPosition.Top).Content("Clear Filters"))

Note: The helpers cannot access other helpers like the Kendo UI or like Html.TextBox() but there is a work around. You need to pass the view page into the helper and use page.Html. where you normally just had Html.
Make sure you remember the using's

To call from your views use


Creating Kendo UI Helper Extensions

If you find yourself setting up a Kendo UI object the same on many views then it may be best to create an helper extension.
Best with an example. Create a new file to hold the following class

using System.Web.Mvc;  
using Kendo.Mvc.UI;

namespace CB.Web {  
 public static class CBHtmlHelperExtensions {

  public static Kendo.Mvc.UI.Fluent.WindowBuilder CBKendoWindow(this HtmlHelper helper, string title, int width, int height) {
   if (width == 0) width = 900;
   var wdw = helper.Kendo().Window()
    .Actions(actions => actions.Maximize().Close())
    .Events(events => events.Refresh("CBwindow.Refresh"));

   if (height == 0) return wdw;
   return wdw.Height(height);

Then in the view all you need is
@(Html.CBKendoWindow("", 900, 0))

Above is for a Kendo window but you can use the Fluent builder of any kendo UI.
Also remember its still a builder so you could still add to it like
@(Html.CBKendoWindow("Copy Paste", 0, 0).Scrollable(true))


Above referring to version
Telerik Kendo UI Professional Q1 2015
Telerik UI for ASP.NET MVC Q1 2015

comments powered by Disqus