Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc create my own html helper, how can i access httpcontext?

Tags:

asp.net-mvc

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

like image 658
rj. Avatar asked Apr 22 '10 19:04

rj.


2 Answers

public static class HtmlHelperExtensions
{
    public static HttpContextBase GetContext(this HtmlHelper htmlHelper)
    {
        return htmlHelper.ViewContext.HttpContext;
    }
}
like image 90
bradjive Avatar answered Nov 07 '22 17:11

bradjive


You might also use: System.Web.HttpContext.Current.Request.RequestContext

like image 44
GitteTitter Avatar answered Nov 07 '22 15:11

GitteTitter