Xin chào các bạn!

Lâu quá không post bài nên hôm nay post một bài hướng dẫn các bạn về Area trong mvc khi tạo mới một dự án.

Vậy Area là gì? khi nào thì dùng nó. Mình nói đơn giản như sau. ví đự án bạn có nhiều module. và có nhiều nhóm làm thì mỗi area sẽ tuơng tự như một module.
ví dụ đơn giản: website ai cũng có 2 phần nhỉ. giao diện người dùng và giao diện trang admin để quản lý. vậy mình sẽ làm một ví dụ làm 2 module:
+ Main -> tức là giao diện dành cho người dùng. đường link mặc định là /{Controller}/{Action} chứ không phải là /Main/{Controller}/{Action} đâu nha. chút sẽ hướng dẫn cụ thể
+ Admin -> tức là phần quản trị. đường link mặc định là /Admin/{Controller}/{Action}

B1:
Tạo project mvc4 (mvc5 hoặc hơn tùy bạn)

B2:
Chọn MVC rồi ấn OK (lưu ý bạn change Authentication là none nhé. đỡ sinh ra nhiều code. muốn dùng thì add sau)

B3:
- Xóa hết các thư mục Controller,Model,View bên ngoài đi

- Tạo 2 Area là Admin và Main

B4: config để area Main là router mặc định cho website
- Mở file: RouterConfig.cs trong thư mục APP_Start sửa lại code thành
Mã:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace WebApplication1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //code cu
            //routes.MapRoute(
            //    name: "Default",
            //    url: "{controller}/{action}/{id}",
            //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            //);

            //code moi
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "WebApplication1.Areas.Main.Controllers" }
            ).DataTokens.Add("Area", "Main");
        }
    }
}
- Mở file: MainAreaRegistration.cs trong area Main sửa lại code thành
Mã:
using System.Web.Mvc;

namespace WebApplication1.Areas.Main
{
    public class MainAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "Main";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            //xoa thang nay di. gio config route area Main o file Routeconfig
            //context.MapRoute(
            //    "Main_default",
            //    "Main/{controller}/{action}/{id}",
            //    new { action = "Index", id = UrlParameter.Optional }
            //);
        }
    }
}
B5: Bạn tạo 2 Controller Home và acction Index để test thử ở 2 area;


Giờ chạy project và test thử 2 đường link:
- /Home/Index
- /Admin/Home/Index

Xin cảm ơn!