tags:

views:

169

answers:

1

Hi,

I've come across two recommendations for creating custom html helpers: either extend an existing one, or write your own class.

I'd prefer to keep my custom code separated, it seems a bit sloppy to extend helpers for a decent-size application.

But the benefit I see in extending is that 'This HtmlHelper helper' is passed as a parameter, through which I can get ViewContext.HtmlContext.

My question is, how can I roll my own helper class and still have ViewContext.HtmlContext available to me?

Thanks!

Edit: What I am looking to do, is create "MyHelperClass" which will render some custom objects as html. I don't see a need to "Extend" an Html helper since i'm not using anything that it offers me. The only reason I have to extend htmlhelper currently is to access httpcontext, as you've shown. But my question was, how can i access httpcontext in my own class, without extending an existing helper. thanks

+3  A: 
public static class HtmlHelperExtensions
{
    public static HttpContextBase GetContext(this HtmlHelper htmlHelper)
    {
        return htmlHelper.ViewContext.HttpContext;
    }
}
bradjive
'cannot convert type system.web.httpcontextbase to system.web.httpcontext' .. should this method be returning httpcontextbase instead?
rj
@rj, yes you are correct, it should
mxmissile
Yes, HttpContextBase, I apologize. I doubt you would actually use this method. It is more of an example of using a static class and method to access the HtmlHelper.ViewContext.HttpContext object when inside an extension method. It is common for projects to have many methods in the static HtmlHelperExtensions class. (however, I'll reserve my dislike of extension methods in general for another thread).
bradjive
hi, while this code will work in a class that extends an existing html helper, it doesn't quite answer my question.What I am looking to do, is create "MyHelperClass" which will render some custom objects as html. I don't see a need to "Extend" an Html helper since i'm not using anything that it offers me.The only reason I have to extend htmlhelper currently is to access httpcontext, as you've shown. But my question was, how can i access httpcontext in my own class, without extending an existing helper.thanks
rj
I guess I'm having a hard time understanding your question. If you just need your httpcontext, why not use System.Web.HttpContext.Current then?
bradjive