Inheriting from HtmlHelper instead of Extending it

2019-05-24 06:52发布

问题:

I'm creating a set of helpers for rendering compatible Twitter Bootstrap html. As I see it, I have two options when it comes to how to group these methods together:

  • Extend the HtmlHelper prefixing the methods with TB
  • Create a new class TBootHelper which contains the methods

In the second case, to get the TBoot helper available, the developer would add

<pages pageBaseType="Twitter.Bootstrap.Mvc.TBootViewPage">

To it's ~/Views/web.config (as pointed by @darin)

Or instantiate the helper when it's needed

@using Twitter.Bootstrap.Mvc
var TBoot = new TBootHelper<TModel>(Html);

My question is, Should I create a TBootHelper class or just add methods to the HtmlHelper?

回答1:

I'd go with creating a custom TBootHelper and a custom base view that all views will inherit from and which will have a property of type TBootHelper.

And instead of forcing the developer to add @inherits Twitter.Bootstrap.Mvc.TBootViewPage<TModel> to every single Razor template in which he wants to use this custom helper, I would add it to the ~/Views/web.config file, once and for all:

<pages pageBaseType="Twitter.Bootstrap.Mvc.TBootViewPage">

and then in the views:

@model MyViewModel
@TBoot.Foobar()