views:

21

answers:

1

I wanted to add an extension method to the HtmlHelper class so that developers could generically retrieve and AreaActionLink<T> without having to add the new { area = "MyArea" } each time as well as not have to specify a Controller. This all works well and good if I specify the namespace or put the namespace of the Area Controller in the Web.config.

For instance if I change the Area controller namespace to My.Web.Controllers rather than My.Web.MyArea.Controllers it throws a 404 but if I use the namespace it resolves properly.

public static MvcHtmlString AreaActionLink<T>(this HtmlHelper helper, string linkText, string actionName, object routeValues, object htmlAttributes) where T : IController
{
    RouteValueDictionary routes = new RouteValueDictionary(routeValues);
    string area = typeof(T).GetArea();
    if (!routes.ContainsKey("area"))
        routes.Add("area", area);

    return helper.ActionLink(linkText, 
        actionName, 
        typeof(T).Name.Replace("Controller", string.Empty), 
        routes, 
        htmlAttributes as Dictionary<string, object>);
}

This works if the namespace is fully qualified when calling AreaActionLink

namespace My.Web.Areas.MyArea.Controllers
{
    [Area("MyArea")]
    public class OtherPlaceController : Controller
    {
        //...
    }
}

and called like this:

<%=Html.AreaActionLink<OtherPlaceController>("Link Text", "MyAction")%>

but if I try to flatten the namespace hierarchy so I don't have to add a new namespace for ever Area it throws a 404.

namespace My.Web.Controllers
{
    [Area("MyArea")]
    public class OtherPlaceController : Controller
    {
        //...
    }
}

It seems that the .Areas portion of the namespace is important but I can't figure out why...

+1  A: 

As I'm sure you've become accustomed to, by default ASP.NET MVC is very much dependent on directory structure (controllers need to be in "Controllers" folder, views in "Views", etc.) This is just more of the same. Your areas should be in separate folders -- that's actually one of the main reasons to have them! :)

Kirk Woll
Yes, my areas are in sub folders from the root but I was trying to get flat namespaces so that I didn't have to fully qualify the namespace when calling my extension method or have to add each new Area to the web.config. I guess it's a one time thing so it's not *too* bad.
hunter