Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Sitecore Razor / Glass Attribute Helper Methods Fluent API

After blogging about creating some Sitecore Glass Attribute Helper Methods (Blog Post) to help front end developers add HTML attributes to Razor / Sitecore Glass Mapper controls. I had an interesting comment from Jim Noellsch, mentioning about turning the helper classes into a Fluent API.

With a Fluent API, A developer is able to chain up multiple method calls, by returning the object on each method. See an example here for a better explanation than I can give http://www.codeproject.com/Articles/640997/Fluent-interfaces-and-Method-Chaining-in-Csharp.

In the context of my attribute helper, this means that a developer can chain up multiple attributes into a single Dictionary. This gives the developer more flexibility of which attributes they want to use and are able to mix and match them.

Below is the code for the Fluent API version of the html attribute helper classes.

In the example .cshtml file you can see the API in use, as you can see we can chain up as many attribute methods calls are we like. To return the underlying Dictionary which is required for the @html helper controllers we call the Render() method.