15.01.29-MVC中用Areas分解项目

在MVC项目上右键->新建->区域(Areas)...,将会自动生成Areas文件夹,并在文件夹下创建Model+Controller+View的mvc框架。在Views文件夹中,自动生成web.config,同时在父文件夹下自动生成xxxAreaRegistration.cs文件。如图:

在testAreaRegistration.cs里面自动生成对当前区域的路由规则。为了避免此路由规则和默认的App_Start下面的RouteConfig.cs里面的default路由规则相冲突,最好在两个规则中添加namespace参数:

在Global.asax的Application_Start()函数下面添加一行:AreaRegistration.RegisterAllAreas();

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

如此,Areas拆分管理实现。

但是,在实际应用中,项目有身份验证。而所有的View全部使用相同的布局。那么,问题来了,在进入Area下面的窗口后,再点击上面的_Layout菜单,可以看到所有的链接全部变成Area下面,刚才点击的那个窗口的了。例如Log Off的链接变成:

这个时候,我们需要修改Share文件架下面的布局文件。

<div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
        <li>@Html.ActionLink("About", "About", "Home",  new { area = "" }, null)</li>
        <li>@Html.ActionLink("Contact", "Contact", "Home",  new { area = "" }, null)</li>

        @if (Request.IsAuthenticated && User.IsInRole("Admin"))
        {
            <li>@Html.ActionLink("RolesAdmin", "Index", "RolesAdmin",  new { area = "" }, null)</li>
            <li>@Html.ActionLink("UsersAdmin", "Index", "UsersAdmin",  new { area = "" }, null)</li>
        }
    </ul>
    @Html.Partial("_LoginPartial")
</div>

带红色下划线处,为新添加的RouteValue。

原文地址:https://www.cnblogs.com/icyJ/p/4260487.html