1

Our project uses a lot of custom HtmlHelper extension methods to be referenced in views like:

@Html.MyHelperMethod()

However, I'd like to keep them separated out from the system ones and be able to do something like either of the following:

@Html.MyApp.MyHelperMethod()
@MyAppHtml.MyHelperMethod()

By following Razor HtmlHelpers with sub-sections? I was able to implement something like

@Html.MyApp().MyHelperMethod()

This just doesn't look as pretty with MyApp() as a function haha. So I set out to make my own class. I want it to be able to access the ViewContext just like HtmlHelper does:

public class MyHtmlHelper
{
    public ViewContext ViewContext { get; private set; }

    public MyHtmlHelper(ViewContext viewContext)
    {
        this.ViewContext = viewContext;
    }

    public MvcHtmlString MyHelperMethod()
    {
        //... Do something that accesses this.ViewContext
    }
}

However, I have no idea what to inherit and override (ViewPage?), where to put a MyHtmlHelper property or where to initialize. The other alternative idea I can come up with is create a BaseModel object all models inherit from and add a MyHtmlHelper property in it in order to do

@Model.MyAppHtml.MyHelperMethod()

This would require every controller method pass the context to the model object (in order to reference ViewContext), but this seems like a tedious trade-off. Any other ideas on how to "subsection" the helper methods not using functions?

UPDATE: Thanks to answers here, I found a detailed example in creating a custom HtmlHelper class like this: Changing Base Type Of A Razor View

Community
  • 1
  • 1
Roury
  • 13
  • 5

2 Answers2

1

You need to create a class that inherits WebViewPage and adds your custom property, then change all of your views to inherit that class.

You can change the default base class in Web.config.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Thanks this worked for me. I found a detailed guide on doing exactly this and a custom HtmlHelper: [Changing Base Type Of A Razor View](http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx). – Roury May 01 '13 at 18:43
0

I have the skeleton how you can proceed as follows

public MtWebViewPage<TModel> : WebViewPage
{
  public HtmlHelper<TModel> MyHtml {get;set;}
}
Dan Hunex
  • 5,172
  • 2
  • 27
  • 38