简体   繁体   中英

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?

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM