1、背景
微軟在MVC中引入了Area概念,用於復雜項目的分工開發。如一個MVC項目中Controller過多時,就會導致項目中包含大量的Controller+View+Model,無論是查找還是調試都比較麻煩。因此微軟引入了Area概念,不過默認也是在同一個項目中創建多個Area區域,本文主要講解根據業務需要創建不同的Area項目,每個項目中都包含
Controller+View+Model,也可以調用各自獨立的業務邏輯和數據訪問層,並通過主MVC項目進行導航
2、使用步驟
2.1 創建一個shell(殼)的MVC項目,作為主項目,命名為
Web.UI
2.2 在主項目中創建一個Area文件夾
2.3 創建一個名稱為
Web.UI.Area1的MVC空項目,創建位置位於主項目的Area文件夾下,並刪除如global.asax等文件。新建
Web.UI.Area1AreaRegistration.cs類文件,設置路由,代碼如下:
namespace Web.UI.Area1
{
public class Area1AreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Web.UI.Area1";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Web.UI.Area1",
"Web.UI.Area1/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "Web.UI.Area1.Controllers" }
);
}
}
}
{
public class Area1AreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Web.UI.Area1";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Web.UI.Area1",
"Web.UI.Area1/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "Web.UI.Area1.Controllers" }
);
}
}
}
創建一個測試Controller如Area1Controller.cs,並創建一個Action命名為Index,可顯示任意信息,用於表示導航到此頁面
2.4 設置
Web.UI.Area1的生成事件,將本項目生成的dll同時拷貝到
Web.UI項目的bin目錄下
項目名稱-->右鍵屬性-->生成事件-->后期生成事件命令行輸入以下內容:
xcopy /r /y $(TargetDir)*.dll $(SolutionDir)\Web.UI\bin
項目名稱-->右鍵屬性-->生成事件-->后期生成事件命令行輸入以下內容:
xcopy /r /y $(TargetDir)*.dll $(SolutionDir)\Web.UI\bin
xcopy /r /y $(TargetDir)*.pdb $(SolutionDir)\Web.UI\bin
2.5 在
Web.UI項目任一View頁面添加下面鏈接代碼,導航到
Web.UI.Area1-->
Area1Controller-->Index對應的View頁面
其中:
Web.UI.Area1為Area的名稱;Area1為Controller名稱;Index為Action名稱
@Html.ActionLink("
導航到Area1
,