tags:

views:

336

answers:

2

Is it possible to add a custom helper object to the ViewPage class, so I can use it inside the view page markup (just like Html, Url and Ajax) ? This helper object also needs some data from a custom controller. (which should be possible through the ViewContext property I think)

A: 

Create new class, derive it from System.Web.Mvc.ViewPage, add new property for custom helper and override InitHelpers() method. For example:

public class CustomViewPage : System.Web.Mvc.ViewPage
{
    public YourCustomHelper CustomHelper
    {
        get;
        set;
    }

    public virtual void InitHelpers()
    {
        CustomHelper = new YourCustomHelper(ViewContext);

        base.InitHelpers();
    }
}


public class YourCustomHelper
{
    public YourCustomHelper(ViewContext viewContext)
    {
        if (viewContext == null) {
            throw new ArgumentNullException("viewContext");
        }

        ViewContext = viewContext;
    }

    public ViewContext ViewContext
    {
        get;
        private set;
    }
}
eu-ge-ne
thanks eugene, i also created a custom controller context and i access it like this: CustomHelper = new YourCustomHelper(ViewContext.Controller.ControllerContext as CustomControllerContext);
A: 

You can do this very easily with an extension method (now available in .Net 3.5) Consider a class like this:

public static class ViewPageExtensions
{
    public static string DoSomething(this ViewPage page, string input)
    {
        // Do something clever with the page
    }
}

As long as your ViewPageExtensions class is visible to the namespaces you've imported on your ViewPage.aspx that you are working on, you should be able to access the DoSomething method directly, without referring to the ViewPageExtensions class.

Jeff Fritz
I attempted this myself - nice in theory, but it appears this doesn't actually work in practice. The IDE does not recognize the extension methods. Oddly, from your view files, you can do stuff like <%=this.DoSomething("input")%> but not <%=DoSomething("input")%> which is not recognized by intellisense, and results in a runtime exception.
mindplay.dk