Search code examples
asp.net-mvcrazorfluent-interface

How to implement fluent api in ASP.NET MVC?


I want to implement fluent api to my mvc sites. I got the basics. So implement object library such as:

public class UIElement{/*...*/}
public class ButtonBase : UIElement{/*...*/}
public class LinkButton : ButtonBase {/*...*/}

  public static class Extensions
  {
    public static T UIElementMethod<T>(this T element, string title)
      where T : UIElement
    {
      return element;
    }

    public static T ButtonBaseMethod<T>(this T element, string title)
      where T : ButtonBase
    {
      return element;
    }

    public static T LinkButtonMethod<T>(this T element, string title)
      where T : LinkButton
    {
      return element;
    }
  }

But how to use it in razor view without some flush method calling.

@Html.UIproject().LinkButton()
    .UIElementMethod("asd")
    .ButtonBaseMethod("asd")
    .LinkButtonMethod("asd")

But it returns the name of the class. I tried to make an implicit operator to MvcHtmlString but it's not called. Any idea how to achieve this. How to know it's the and of the chain. I like the way how the Kendo UI work.

Thanks,
Péter


Solution

  • Your UIElement classes need to implement the IHtmlString interface. This interface's ToHtmlString method gets called by Razor and should return an HTML-encoded string.

    So I would implement this on the abscract base UIElement and create RenderHtml method which can be implemented by the concrete LinkButton, etc. classes:

    public abstract class UIElement : IHtmlString 
    {
        public string ToHtmlString()
        {
            return RenderHtml(); // This should return an HTML-encoded string.
        }
    
        public override string ToString()
        {
            return ToHtmlString();
        }
    
        protected abstract string RenderHtml();
    }
    

    If you check KendoUI in Reflector/JustDecompile/dotPeek in the WidgetBase class you will see the same pattern.