標籤:text 版本 訪問 pat div 函數 刪除 code 商務邏輯
MVC本身提倡的就是關注點分離。但是當項目本身的商務邏輯足夠複雜,如果所有的商務邏輯都寫個Controller檔案夾下面的時候,你會看到非常龐大的各種命名的Controller,這個時候地區的作用就非常明顯了,將不同的模組通過地區加以區分,簡單明了。
添加地區:
建立的MVC工程是沒有地區的。點擊項目右鍵->添加->地區,輸入地區名稱。.net會自動在項目下添加“Areas”檔案夾,並在該檔案夾下建立對應的地區的檔案夾。建立一個“test”的地區,在地區下添加控制器“default”,將“default”控制器內容改為:
[RouteArea("test")] [RoutePrefix("default")] public class Default1Controller : Controller { [Route("index")] public ActionResult Index() { return View(); } }
註冊路由:
MVC項目建立後悔自動組建檔案“Global.asax”檔案。找到Application_Start函數中的RouteConfig.RegisterRoutes(RouteTable.Routes).進入RegisterRoutes,在其中添加代碼 routes.MapMvcAttributeRoutes()
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes();//註冊屬性路由 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
刪除AreaRegistration:
當你建立新的地區時,工程會自動在地區下建立AreaRegistration。比如建立default控制器後,test地區的檔案夾下會自動產生“testAreaRegistration.cs”,這個檔案是MVC5以前的版本用來註冊路由的。在MVC5中由於在Global.asax註冊了屬性路由,所以可以直接把這個檔案刪了,否則也會出現找不到路由的錯誤。內容大致是:
public class testAreaRegistration : AreaRegistration { public override string AreaName { get { return "test"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "test_default", "test/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } }
然後就可以直接通過路由的方式訪問Areas中的控制器了:
<a class="btn btn-default" href="/test1/default/index">test »</a>
【轉】MVC5中的地區(Areas)