MVC下使用Areas

(一) 为什么要分离

  MVC项目各部分职责比较清晰,相比较ASP.NET Webform而言,MVC项目的业务逻辑和页面展现较好地分离开来,这样的做法有许多优点,比如可测试,易扩展等等。但是在实际的开发中,随着项目规模的不断扩大,Controller控制器也随之不断增多。如果在Controllers文件夹下面有超过两位数controller,即便采用良好的命名规范,或者用子文件夹的形式区分不同功能的控制器,还是会影响项目的可阅读性和可维护性。因此,在一些场景下,如果能把与某功能相关的文件分离到一个独立的项目中是非常有用的。Asp.Net MVC提供了Areas(区域)的概念达到这一目的。

(二) 新建一个项目

  新建一个项目:文件->新建->项目->名称“ Sol_Test_Code”

  

  选择MVC

  新建控制器“HelloWorld”

  

  修改代码:

public class HelloWorldController : Controller
    {
        // 
        // GET: /HelloWorld/

        public string Index()
        {
            return "This is my default action...";
        }

        // 
        // GET: /HelloWorld/Welcome/ 

        public string Welcome()
        {
            return "This is the Welcome action method...";
        }
    }

  

执行调试(Ctrl+F5):结果如下

  

 然后在项目上右键->添加->Areas,输入"Admin",并新建控制器“HelloWorld”  图如下:

  

修改HelloWorld控制器代码:

namespace Sol_Test_Code.Areas.Admin.Controllers
{
    public class HelloWorldController : Controller
    {

        public string Index()
        {
            return "This is my Admin default action...";
        }

        // 
        // GET: /HelloWorld/Welcome/ 

        public string Welcome()
        {
            return "This is Admin the Welcome action method...";
        }
    }
}

 执行调试(Ctrl+F5):结果如下

  

但是此时,若是执行http://localhost:20839/helloworld,就会报错,结果如下

  

 此时应该调整AdminAreaRegistration.cs 和RouteConfig.cs代码

AdminAreaRegistration.cs 修改如下:  

 public override string AreaName 
        {
            get 
            {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new string[] { "Sol_Test_Code.Areas.Admin.Controllers" }
            );
        }

  

 RouteConfig.cs修改如下:

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new
                {
                    controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional
                }
                //,namespaces: new[] { "Sol_Test_Code.Controllers" }             
            );
        }

 执行调试(Ctrl+F5):结果如下 

  

 

  至此已完成!

猜你喜欢

转载自www.cnblogs.com/hyshareex/p/10330532.html