mmilan
mmilan

Reputation: 1778

How to use ActionLink() inside an htmlhelper extension method MVC4

I have a method inside of an HtmlHelper that needs to generate a Link

private static string IntentarGenerarLink<T>(HtmlHelper helper, T d, TableHeaderDetails h, string value)
{
  if (h.Link != null)
  {
    var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
    var url = urlHelper.Action(h.Link.Controller, h.Link.Action, new { id = d.GetType().GetProperty(h.Link.ID).GetValue(d,null) });
  }
  return value;
}

urlHelper.Action is returning a relative path and i need a complete URL, to solve this I have tried to use ActionLink() but I cant access it from inside of my HtmlHelper extension method.

what do i need to change to be able to use the ActionLink method?

Upvotes: 1

Views: 578

Answers (2)

AdaTheDev
AdaTheDev

Reputation: 147224

You should be able to get the complete URL by using another of the overloads of urlHelper.Action - one where you also pass in the scheme. By passing in the scheme, you should get back the full URL, not a relative URL.

var url = urlHelper.Action(h.Link.Controller, h.Link.Action, 
    new { id = d.GetType().GetProperty(h.Link.ID).GetValue(d,null) }, 
    helper.ViewContext.RequestContext.HttpContext.Request.Url.Scheme);

Upvotes: 0

John H
John H

Reputation: 14655

Make sure you're using both the following using statements:

using System.Web.Mvc;
using System.Web.Mvc.Html;

Upvotes: 2

Related Questions