如何在ASP.NET MVC中实现流畅的api?

时间:2013-04-21 05:43:44

标签: asp.net-mvc razor fluent-interface

我想为我的mvc网站实现流畅的api。我得到了基础知识。 因此实现对象库,如:

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;
    }
  }

但是如何在没有一些flush方法调用的剃刀视图中使用它。

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

但是它返回了类的名称。我试图为MvcHtmlString创建一个隐式运算符,但它没有被调用。 任何想法如何实现这一点。如何知道它是链和链。我喜欢Kendo UI的工作方式。

谢谢,
彼得

2 个答案:

答案 0 :(得分:4)

您的UIElement类需要实现IHtmlString接口。 Razor调用此接口的ToHtmlString方法,并返回HTML编码的字符串。

所以我会在abscract base UIElement上实现这个并创建RenderHtml方法,这个方法可以由具体的LinkButton等类来实现:

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();
}

如果你在WidgetBase类的Reflector / JustDecompile / dotPeek中检查KendoUI,你会看到相同的模式。

答案 1 :(得分:0)

在这种特殊情况下,我没有尝试过,但您可以使用隐式强制转换从流畅的构建器转换为您需要的对象(请参阅此blog)。