How to specify default Area to Html.BuildUrlFromExpression call
-
25-09-2019 - |
Question
I have problem like link text
All of my links look like this: htp//site/controller/action/id
I just added Area called BackEnd.
My Controller:
[ActionLinkArea("")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
Now when I'm try to get some conroller URL using
@Html.ActionLink<HomeController >(c => c.Index(), "Home")
All works fine, and url is htp://site/HomeController/Index/
But when I use extension method from Microsoft.Web.Mvc.dll
@Html.BuildUrlFromExpression<HomeController>(c => c.Index())
I get URL htp://site/BackEnd/HomeController/Index/
How can I get URL without Area using BuildUrlFromExpression and why ActionLink works fine but BuildUrlFromExpression not?
Solution
It is Microsoft bug.
http://aspnet.codeplex.com/workitem/7764
The method uses internally LinkBuilder.BuildUrlFromExpression(). The latter calls routeCollection.GetVirtualPath(context, routeValues) instead of routeCollection.GetVirtualPathForArea(context, routeValues); which causes invalid results when using areas.
I did it and method return correct URL
OTHER TIPS
I have better answer!
public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height, string alt)
where T : Controller
{
var expression = action.Body as MethodCallExpression;
string actionMethodName = string.Empty;
if (expression != null)
{
actionMethodName = expression.Method.Name;
}
string url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action(actionMethodName, typeof(T).Name.Remove(typeof(T).Name.IndexOf("Controller"))).ToString();
//string url = LinkBuilder.BuildUrlFromExpression<T>(helper.ViewContext.RequestContext, helper.RouteCollection, action);
return string.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" alt=\"{3}\" />", url, width, height, alt);
}
<%=Html.Image<ClassController>(c => c.Index(), 120, 30, "Current time")%>