Custom Attributes Binding
The Telerik UI for ASP.NET MVC Menu enables you to apply model binding to populate its items dynamically from the server. You can also bind the HTML attributes of the Menu items to fields from the passed Model.
With the MenuItemFactory
class you can construct the menu items and their corresponding attributes. Afterwards, you can apply client-side logic based on the item selection.
The following example illustrates how to bind custom attributes.
-
Make sure that you have supplemented the Menu items from the controller side.
Controller.cspublic ActionResult Menu_Bind_Attributes() { var categories = categoryService.GetCategories(); return View(categories); }
-
Within the Razor View, define a custom method that will construct the items in a format consumable by the Menu. Use the
MenuItemFactory
class.Razor@model IEnumerable<Kendo.Mvc.Examples.Models.Category> @functions { void GenerateProductItems(Kendo.Mvc.UI.Fluent.MenuItemFactory productItems, Category category) { foreach (var product in category.Products) { productItems.Add() .Text(product.ProductName) .HtmlAttributes(new { categoryid = product.CategoryID, productid = product.ProductID, unitprice = product.UnitPrice, unitsinstock = product.UnitsInStock }); } } }
-
Inside the boundaries of the Menu, supplement the composed items by using the
Items()
configuration method.Razor@model IEnumerable<Kendo.Mvc.Examples.Models.Category> @functions { void GenerateProductItems(Kendo.Mvc.UI.Fluent.MenuItemFactory productItems, Category category) { ... } } @(Html.Kendo().Menu() .Name("myMenu") .Items(items => { foreach (var category in Model) { items.Add() .Text(category.CategoryName) .HtmlAttributes(new { categoryid = category.CategoryID, title = category.Description }) .Items(productItems => { GenerateProductItems(productItems, category); }); } }) )
-
Optional To perform custom client-side logic based on the constructed attributes, handle the
Select
event of the Menu.Razor@model IEnumerable<Kendo.Mvc.Examples.Models.Category> @functions { void GenerateProductItems(Kendo.Mvc.UI.Fluent.MenuItemFactory productItems, Category category) { ... } } @(Html.Kendo().Menu() .Name("myMenu") .Events(events => events .Select("onMenuSelect") ) .Items(items => { foreach (var category in Model) { items.Add() .Text(category.CategoryName) .HtmlAttributes(new { categoryid = category.CategoryID, title = category.Description }) .Items(productItems => { GenerateProductItems(productItems, category); }); } }) )
For a complete example on the Custom Attributes Binding, refer to the demo on custom attributes binding of the Menu.