如何为抽象基类的派生类定义asp.net Htmlhelper扩展?

时间:2014-01-03 21:51:53

标签: asp.net-mvc asp.net-mvc-5

换句话说,我想做以下事情:

public abstract class Shape {
    public virtual RenderHTML();
}

public class Circle : Shape {
    public override RenderHTML() {}
}  

public class Square : Shape {
    public override RenderHTML() {}
}

public class MyViewModel {
    public Shape shape;
}

// single call to render HTML for whatever shape is needed
// should call on render method for Circle or Square depending on type of Shape
@Html.RenderShape(Model.shape)

我该怎么做? 我不知何故需要将实例传递给HTML帮助器。

编辑:找到了类似的答案here

1 个答案:

答案 0 :(得分:2)

以下是如何实现这样的基本实现:

public static class HtmlHelperExtensions
{
    public static IHtmlString RenderShape(this HtmlHelper helper,
        Shape shape)
    {
        return MvcHtmlString.Create(shape.RenderHtml());
    }
}

其中RenderHtml()将返回带有未编码HTML的字符串。