ASP. NET MVC 2.0-1. Creation and execution of areas

Source: Internet
Author: User
Tags actionlink

Transferred from: http://www.cnblogs.com/terrysun/archive/2010/04/13/1711218.html

ASP. NET MVC 2.0-1. Creation and execution of areas

Areas is one of the many new features introduced in the ASP. 2.0 release, which can help you divide a larger Web project into several components, area. The ability to implement area can have two organizational forms:

    1. Create a areas in 1 ASP. 2.0 project.
    2. Create multiple ASP. 2.0 project, each project is an area.

The 2nd kind of structure is more complex, but the 1th structure can also achieve the parallel development between each area, do not affect each other, so the 2nd method is not recommended.

For example, the default template for ASP. NET MVC 2.0:

1. first create a new project for ASP. NET MVC 2.0, click the right mouse button on project to select Add->area, enter the name of area in the open window (for example: Profile), click the Add button, You will then see the structure below.

The structure of the area named profile is the same as the structure of the controllers,models and views under the root directory, and the only difference is that there is one more ProfileAreaRegistration.cs file under profile. It inherits from the Arearegistration class, and profilearearegistration must implement the AreaName attribute in the arearegistration class and Registerarea ( AreaRegistrationContext context) method

Using System.web.mvc;namespace asp.net_mvc_2_test.areas.profile{Public    class Profilearearegistration: Arearegistration    {public        override string AreaName        {            get            {                return ' profile ';            }        }        public override void Registerarea (AreaRegistrationContext context)        {            context. MapRoute (                "Profile_default",                "Profile/{controller}/{action}/{id}",                new {action = "Index", id = Urlparameter.optional}            );}}}    

The AreaName property is used to define the name of the area, and the Registerarea (AreaRegistrationContext context) method can be seen in the browser's address bar where the URL is styled as profile/{controller}/ {Action}/{id}, is a 4-level construct, as long as the context. MapRoute (...) Switch

public override void Registerarea (AreaRegistrationContext context)        {            context. MapRoute (                "Profile_default",                "Profile/{action}/{id}",                new {controller = "controller name to access", action = " Index ", id = urlparameter.optional}            );        }

The style of the URL is then changed to a level three structure profile/{action}/{id}.

2. Modify the Views/shared/site.master file in the root directory and add a menu item named o"Your profile" and specify the name of area, which is the name of the area in the example.

<ul id= "Menu" >                                  <li><%= html.actionlink ("Home", "Index", "Home", new {area = ""}, NULL)%></li& gt;                    <li><%= html.actionlink (' Your profile ', ' viewprofile ', ' profile ', new {area = ' profile '}, NULL)%></LI> ;                    <li><%= html.actionlink (' about ', ' about ', ' Home ', new {area = ' "}, NULL)%></li></ul>

Note: Home and about do not belong to any area, but you also want to declare the area through an anonymous object, and if you do not declare area, when you enter a view of profile, the URL of home and about will change to Profile/home. Profile/about, when you click Home or about, there will be an exception, so when a link on the page does not belong to any area and is likely to be available in more than one area, be sure to add new {area = "}

3. only match the correct route to show that the route in the View,area in area is already configured, but how is it added to the routetable?

  3.1   first Application_Start in Global.asax.cs () Method called the Arearegistration.registerallareas () method, this method of the landlord is to find all inherited arearegistration The class, and executes the Registerarea (...) method to complete the registration

public static void Registerallareas () {            registerallareas (null);        }        public static void Registerallareas (object state) {            registerallareas (routetable.routes, New Buildmanagerwrapper () , state);        }        internal static void Registerallareas (RouteCollection routes, Ibuildmanager BuildManager, object state) {            list< type> arearegistrationtypes = typecacheutil.getfilteredtypesfromassemblies (_typecachename, Isarearegistrationtype, BuildManager);            foreach (Type arearegistrationtype in arearegistrationtypes) {                arearegistration registration = (arearegistration) Activator.CreateInstance (arearegistrationtype);                Registration. Createcontextandregister (routes, state);            }        }

    3.1.1  Typecacheutil.getfilteredtypesfromassemblies (...) method is used to find all inherited arearegistration class:

public Static list<type> getfilteredtypesfromassemblies (string cachename, Predicate<type            > predicate, Ibuildmanager buildManager) {Typecacheserializer serializer = new Typecacheserializer (); First, try reading from the cache on disk list<type> matchingtypes = Readtypesfromcache (Cachena            Me, predicate, buildManager, serializer);            if (matchingtypes! = null) {return matchingtypes; }//If reading from the cache failed, enumerate through every assembly looking for a matching type mat Chingtypes = Filtertypesinassemblies (BuildManager, predicate).            ToList ();            Finally, save the cache back to disk Savetypestocache (CacheName, Matchingtypes, BuildManager, serializer);        return matchingtypes; }

      in Getfilteredtypesfromassemblies (...) method, the matching type is read from the cache first (the cache is used in the. NET Framework 4.0, and the sample program is used by VS2008 in the. NET 3.5 environment, where cached apps are not discussed). Cache no data returned, call Filtertypesinassemblies (...) The List<type> method returns the List<type> object, which is the inherited arearegistration class , the following code is the source of the Filtertypesinassemblies method:

private static ienumerable<type> filtertypesinassemblies (Ibuildmanager BuildManager, Predicate<type> predicate) {//Go through all assemblies referenced by the application and search for Ty            PES matching a predicate ienumerable<type> Typessofar = type.emptytypes;            ICollection assemblies = Buildmanager.getreferencedassemblies ();                foreach (Assembly Assembly in assemblies) {type[] typesinasm; try {typesinasm = assembly.                GetTypes (); } catch (ReflectionTypeLoadException ex) {typesinasm = ex.                Types;            } Typessofar = Typessofar.concat (typesinasm);        } return Typessofar.where (type = Typeispublicclass (type) && predicate (type)); }

Similar to finding Controll, find all the types in all assembly and filter out the type objects that inherit the Arearegistration class through Typeispublicclass and predicate.

3.1.2 in Getfilteredtypesfromassemblies (...) Method if the version of the. Net Framework is not 4.0, the last Savetypestocache (...) Method also does not perform

The Readtypesfromcache (...) will later be on the. Net Framework 4.0. and Savetypestocache (...) To supplement

3.2 Iterates over the returned List<type> object, reflecting the Arearegistration object and calling its Createcontextandregister (...). Method

internal void Createcontextandregister (RouteCollection routes, object state) {            AreaRegistrationContext context = New AreaRegistrationContext (AreaName, routes, state);            String thisnamespace = GetType (). Namespace;            if (thisnamespace! = null) {                context. Namespaces.add (Thisnamespace + ". *");            Registerarea (context);        }

In Createcontextandregister (...) method to create a AreaRegistrationContext object and do it as a registerarea (...) The parameter of the Registerarea method, which is exactly the overridden method in the Arearegistration inheritance class, Registerarea the method whenever the AreaRegistrationContext class's Maproute (...) is called. Method may complete the registration of a new route.

"Sample code Download"

Post a comment#1楼2010-04-13 17:49 | DozerI have seen this part of the source code, there is a problem to solve, do not know can not be able to change the source code.

So, for example, if I have 2 area, can the registration order of the two area be fixed?

From the original view, it is not fixed, because it is the use of reflection to get a set

Do not know what the blogger has a solution? Support (0) objection (0) #2楼2010-04-13 18:01 | HeizivanMark supports (0) against (0) #3楼 [Landlord] 2010-04-13 22:26 | Terry Sun @Dozer
First of all 1th, absolutely cannot modify the source code:)

Fixed is possible, first do not need to create a class inheriting from arearegistration, each area of the route register write to Global.asax.cs, as follows
123456789101112131415161718 publicstaticvoid RegisterRoutes(RouteCollection routes){    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    // Register Arearoutes.MapRoute(                "Profile_default",                "Profile/{action}/{id}",                new{ controller = "Profile", action = "index", id = UrlParameter.Optional }                );     routes.MapRoute(                "Default", // Route name                "{controller}/{action}/{id}",                 new{ controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults            );}
Support (0) against (0) #4楼 [Landlord] 2010-04-13 22:27 | Terry Sun @ Heizivan
:) Support (0) objection (0) #5楼2010-04-13 23:10 | Dozer@Terry Sun
I've never really tried that.

Can you just move it out? I'm going to try. Support (0) objection (0) #6楼2010-04-13 23:40 | Dozer@Terry Sun
After testing, there is a problem, after moving out, the route is normal, but this time the search view will not search under the Areas/myareas/view

Error Support (0) objection (0) #7楼 [Landlord] 2010-04-14 09:07 | Terry Sun @Dozer
Sorry, is I did not explain the white, must declare areaname and save to Route.datatttokens, otherwise can not be located to the corresponding area directory, the following code is two area, first register the profile and then register the blog

1234567891011121314151617181920212223242526272829303132 publicstaticvoid RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            #region Register Areas            // Profile ares.            Route areaProfile = routes.MapRoute(                 "Profile_default",                 "Profile/{action}/{id}",                 new { controller = "Profile", action = "View", id = UrlParameter.Optional}             );            areaProfile.DataTokens["area"] = "Profile";            areaProfile.DataTokens["UseNamespaceFallback"] = true;            // Blog ares.            Route areaBlog = routes.MapRoute(                 "Blog_default",                 "Blog/{action}/{id}",                 new{ controller = "Blog", action = "View", id = UrlParameter.Optional}             );            areaBlog.DataTokens["area"] = "Blog";            areaBlog.DataTokens["UseNamespaceFallback"] = true;             #endregion            routes.MapRoute(                "Default", // Route name                "{controller}/{action}/{id}", // URL with parameters                new{ controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults            );        }

 

(EXT) ASP. NET MVC 2.0-1. Creation and execution of areas

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.