クラスに拡張メソッドを追加してHtmlHelper
、開発者が毎回AreaActionLink<T>
を追加したり、 . 名前空間を指定するか、エリア コントローラーの名前空間を Web.config に配置すると、これはすべてうまく機能します。new { area = "MyArea" }
Controller
たとえば、Area コントローラーの名前空間を404 をスローするMy.Web.Controllers
代わりに変更My.Web.MyArea.Controllers
すると、名前空間を使用すると適切に解決されます。
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>);
}
これは、AreaActionLink を呼び出すときに名前空間が完全修飾されている場合に機能します。
namespace My.Web.Areas.MyArea.Controllers
{
[Area("MyArea")]
public class OtherPlaceController : Controller
{
//...
}
}
そして次のように呼び出されます:
<%=Html.AreaActionLink<OtherPlaceController>("Link Text", "MyAction")%>
しかし、名前空間階層をフラット化しようとすると、新しい名前空間を追加する必要がなくなり、Area は 404 をスローします。
namespace My.Web.Controllers
{
[Area("MyArea")]
public class OtherPlaceController : Controller
{
//...
}
}
名前空間の部分が重要なようですが、.Areas
理由がわかりません...