Use areas to separate ASP. net mvc Projects

Source: Internet
Author: User

Why does it need to be separated?

We know that the responsibilities of the MVC project are clear, compared with ASP. for net webform, the business logic of the MVC project is well separated from the page display. This method has many advantages, such as testability and scalability. However, in actual development, the number of controller controllers increases as the project scale expands. If there are more than two-digit controllers under the controllers folder, even if you adopt good naming rules or distinguish controllers with different functions in the form of subfolders, the project's readability and maintainability will still be affected. Therefore, in some scenarios, it is very useful to separate files related to a function from an independent project. ASP. net mvc provides the areas (region) concept to achieve this goal.

A typical scenario

Web applications usually have two sections: foreground (for users) and background (for administrators). We hope that the URLs starting with/locahost/admin are the backend management addresses, therefore, we may have such a route:

            routes.MapRoute(    //Admin Route                "Admin", // Route name                "Admin/{controller}/{action}/{id}", // URL with parameters                new { controller = "Admin", action = "Index", id = UrlParameter.Optional } // Parameter defaults            );            routes.MapRoute(    //Default Route                "Default", // Route name                "{controller}/{action}/{id}", // URL with parameters                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults            );

Run the program to access locahost/admin and use routedebugger (Asp. net MVC routing debugging helper routedebugger) output information can be seen, the first route (Admin) matched successfully, admincontroller index method is called, but think about it again, you can use/localhost/admin/index to match the second route (default). You can also call the index method of admincontroller! Similarly, the background user management list (/localhost/admin/user/List) is equivalent to (/localhost/user/list ).

First Improvement

To achieve this goal,/localhost/admin/index matches the first route correctly, while/localhost/admin/index does not match the second route. Therefore, you can set conditions for the default route. For more information, see ASP. net mvc Tip #30-create custom route constraints of Stephen Walther. Modify the default route:

            routes.MapRoute(    //Default Route                "Default", // Route name                "{controller}/{action}/{id}", // URL with parameters                new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults                new { controller = new NotEqual("Admin")}            );

The preceding route indicates that admincontroller does not match the default route. Now run the previous two URLs separately and you will find that direct access to/admin/index cannot match any route. By modifying the notequal class, you can easily add multiple "excluded" Controller restrictions for the default route. But don't you think it's so frustrating?

Second Improvement

Here we will go to the topic and use the areas function for separation. Create a project "mymvcareasdemo", right-click the project and choose "add"> "areas", and enter "admin" as follows:

In the areas/admin/controllers folder, create a homecontroller and add an index method and the corresponding View File. Here we can find another benefit of areas: You can add controllers with the same name under different areas. Of course, if you run it like this, you will get an error:

In this case, you need to modify adminarearegistration. CS and Global. asax to add namespace restrictions to the routes:

/Areas/admin/adminarearegistration. CS

           context.MapRoute(                "Admin_default",                "Admin/{controller}/{action}/{id}",                new { action = "Index", id = UrlParameter.Optional },                new string[] { "MyMvcAreasDemo.Areas.Admin.Controllers" }            );

/Global. asax. CS

           routes.MapRoute(    //Default Route                "Default", // Route name                "{controller}/{action}/{id}", // URL with parameters                new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults                new string[] { "MyMvcAreasDemo.Controllers" }            );

In this way, we can put all the controller and view files related to background management under/areas/admin, and so on, and add such files as members, blogs ), forum (Forum) and multiple areas. Each part has its own top-level folder, and physical files are separated to facilitate management.

This method has been greatly improved, but all files are stored in the same project. When the project scale is large, a better development method is to separate different functional modules into different projects as needed, and finally integrate them into a whole. In this way, each project can be independently developed, tested, and released.

Third Improvement

We need to rebuild the existing project:

1. Create a mymvcareasdemo. Admin mvc3 project in the solution and delete the global. asax and web. config files.

2. Create an adminarearegistration class in the root directory and enter the following content:

    public class AdminAreaRegistration : AreaRegistration    {        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 }                            );        }    }

3. Delete the adminarearegistration. CS file and the controllers folder (including homecontroller) under the mymvcareasdemo Project/areas/admin folder)

4. Create a homecontroller In the controllers of the mymvcareasdemo. Admin project.

5. Remember to keep the views under mymvcareasdemo/areas/admin and reference the mymvcareasdemo. Admin project in the mymvcareasdemo project,

Run the program and access/admin/home/index. The admin project takes effect. In this way, all the controllers related to background management can be put into this new project. But soon you will find that a new "problem" appears again:

When you are in mymvcareasdemo. add a new action (such as List) to the homecontroller in admin, and then habitually right-click on it-"add View", you will find the newly added list. the cshtml file appears in mymvcareasdemo. in admin/views/home, the browser will receive an error when you access/admin/home/List: "The View 'LIST' or its master was not found or no view engine supports the searched locations... ". Originally, it will only search for the view in the corresponding directory of the main program mymvcareasdemo. In this way, the scaffolding function provided by the MVC framework is greatly reduced. Of course, you can manually add a view in mymvcareasdemo/areas/admin/views or in mymvcareasdemo. the admin project automatically generates a view and then copies it. Is there a better way?

Fourth Improvement

In order to enable mymvcareasdemo. the view automatically generated by admin is automatically synchronized to the mymvcareasdemo/areas/admin/views folder. You can use "post-build event" in "build event" to open mymvcareasdemo. modify the admin attributes, as shown in:

My local generation event is:

   mkdir "$(SolutionDir)$(SolutionName)\Areas\Admin\Views"   xcopy "$(ProjectDir)Views" "$(SolutionDir)$(SolutionName)\Areas\Admin\Views" /S /E /C /Y

The meaning is actually very simple. I believe everyone can understand it, that is, completely copy all the files in the Views folder of mymvcareasdemo/areas/admin/views to mymvcareasdemo/areas.

Now you can access/admin/home/list again to get the correct result. You can find that list. cshtml has been copied to the mymvcareasdemo/areas/admin/views/home directory.

This is a success! We have successfully separated the front-end and back-end modules into two independent projects, hoping to help you!

 

=== Update ===

Another separation method: Use mvccontrib to separate ASP. net mvc Projects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.