6

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

tereško
  • 58,060
  • 25
  • 98
  • 150
Péter
  • 2,161
  • 3
  • 21
  • 30
  • Please, stop referring to "ASP.NET MVC" simply as "MVC". One is a framework, while other is a language-independent design pattern. It's like calling IE - "the internet" – tereško Apr 21 '13 at 06:32

2 Answers2

4

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
0

I haven't tried it, in this particular situation, but you might be able to use an implicit cast to convert from a fluent builder to the object you need (see this blog).

Ian Mercer
  • 38,490
  • 8
  • 97
  • 133