Omu
Omu

Reputation: 71248

how to get IUrlHelper from inside Html helper

I need the url helper inside an html Helper so I have

IHtmlHelper<T> html and need to get IUrlHelper

I tried this:

html.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelper));

but it returns null

Upvotes: 5

Views: 1452

Answers (1)

Omu
Omu

Reputation: 71248

got the answer here: https://github.com/aspnet/Mvc/issues/5051 so it looks like this:

public static IHtmlContent MyHelper(this IHtmlHelper<T> html){
    var urlHelperFactory = (IUrlHelperFactory)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelperFactory));            
    var urlHelper = urlHelperFactory.GetUrlHelper(aweInfo.Html.ViewContext);

Upvotes: 10

Related Questions