【轉】MVC5中的地區(Areas)

來源:互聯網
上載者:User

標籤: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 &raquo;</a>

 

【轉】MVC5中的地區(Areas)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.