4

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?

Community
  • 1
  • 1
Ivan Korytin
  • 1,832
  • 1
  • 27
  • 41
  • I just have disassembled Microsoft.Web.Mvc and found that this code VirtualPathData virtualPath = routeCollection.GetVirtualPath(context, routeValuesFromExpression); Where routeCollection abd context -we get from HtmlHelper, and routeValuesFromExpression - from expression return value with Area, but routeValuesFromExpression has normal value. – Ivan Korytin Jan 10 '11 at 11:44
  • I have found answer: 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. – Ivan Korytin Jan 10 '11 at 14:07

2 Answers2

3

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

Community
  • 1
  • 1
Ivan Korytin
  • 1,832
  • 1
  • 27
  • 41
2

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")%>
Oleksandr Fentsyk
  • 5,256
  • 5
  • 34
  • 41