AreaActionLink Extension Method and namespace bug?
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开发者_JS百科 that the .Areas
portion of the namespace is important but I can't figure out why...
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! :)
精彩评论