Search code examples
asp.net-mvchtml-helperviewcontext

How to create a custom class similar to HtmlHelper and initialize with ViewContext?


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


Solution

  • 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.