Create and execute ASP. net mvc 2.0-1. Areas

Source: Internet
Author: User
Tags actionlink

Areas is one of the many new features introduced in ASP. net mvc 2.0. It can help you divide a large web project into several components, namely, area. The area function can be implemented in two organizational forms:

    1. Create areas in one ASP. net mvc 2.0 project.
    2. Create multiple ASP. net mvc 2.0 projects. Each project is an area.

The 2nd structures are complex, but the 1st structures can also achieve parallel development between each area without affecting each other. Therefore, we do not recommend the 2nd methods.

Take the default template of ASP. net mvc 2.0 as an example:

1.Create an ASP. net MVC 2.0 project, right-click the project and choose add-> area. In the displayed window, enter the name of the area (for example, profile) and click Add, the following structure is displayed.

The structure of the area named profile is the same as that of controllers, models, and views in the root directory. The only difference is that there is a profilearearegistration. CS file in the profile. It inherits fromArearegistrationClass,ProfilearearegistrationRequiredArearegistrationThe areaname attribute and registerarea (ArearegistrationcontextContext) Method

UsingSystem. Web. MVC;NamespaceASP. net_mvc_2_test.areas.profile {Public classProfilearearegistration:Arearegistration{Public override stringAreaname {Get{Return"Profile";}}Public override voidRegisterarea (ArearegistrationcontextContext) {context. maproute ("Profile_default","Profile/{controller}/{action}/{ID }",New{Action ="Index", Id =Urlparameter. Optional });}}}

The areaname attribute is used to define the name of an area (ArearegistrationcontextThe URL style in the address bar of the browser is profile/{controller}/{action}/{ID}, Which is Level 4. maproute (...) Change

Public override voidRegisterarea (ArearegistrationcontextContext) {context. maproute ("Profile_default","Profile/{action}/{ID }",New{Controller ="Name of the Controller to be accessed", Action ="Index", Id =Urlparameter. Optional });}

The URL style is changed to a third-level profile/{action}/{ID }.

 

2.Modify the views/shared/site. master file in the root directory and add a file namedO"Your profile", and specify the name of the area. In this example, the name of the area is profile.

 <  Ul  ID  = "Menu"> <  Li  >  <%  = Html. actionlink ( "Home" , "Index" , "Home" , New {Area = "" }, Null ) %>  </  Li  > <  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 they must also be declared using an anonymous object. If area is not declared, when you enter a view of the profile, the URL of home and about changes to profile/home, profile/about. If you click home or about, an exception is thrown, therefore, when a link on the page does not belong to any area and may be available to multiple areas, you must addNew{Area =""}

 

3.Only the correct route match can display the view in the area. The route in the area has been configured, but how is it added to the routetable?

3.1First, the arearegistration. registerallareas () method is called in the application_start () method of Global. asax. CS.ArearegistrationAnd execute registerarea (...) Method to complete 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.1Typecacheutil. Getfilteredtypesfromassemblies (...) The method is used to find out all the inheritedArearegistrationType object of the 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 (cachename, predicate, buildmanager, serializer ); If (Matchingtypes! = Null ){ Return Matchingtypes ;} // If reading from the cache failed, enumerate over every assembly looking for a matching type Matchingtypes = filtertypesinassemblies (buildmanager, predicate). tolist ();// Finally, save the cache back to disk Savetypestocache (cachename, matchingtypes, buildmanager, serializer ); Return Matchingtypes ;}

In getfilteredtypesfromassemblies (...) Method, first read the matching type from the cache (the cache is used in. NET Framework 4.0, for exampleProgramUsing vs2008 In the. NET 3.5 environment, we will not discuss cached applications for the moment ). If no data is returned in the cache, filtertypesinassemblies (…) is called (...) The method returns the list <type> object, and the returned list <type> inheritsArearegistrationClass type object, the followingCodeIs the source code 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 types 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 the method used to search for controll, the system finds all types in all assemblies and inherits them by filtering typeispublicclass and predicate.ArearegistrationType object of the class

3.1.2In getfilteredtypesfromassemblies (...) If the. NET Framework version is not 4.0, the last savetypestocache (...) Method will not be executed

Readtypesfromcache (…) under. NET Framework 4.0 (...) And savetypestocache (...) Supplement

 

3.2ReturnsList<Type> Object, reflectedArearegistrationObject and call its createcontextandregister (...) Method

 
Internal voidCreatecontextandregister (RoutecollectionRoutes,ObjectState ){ArearegistrationcontextContext =NewArearegistrationcontext(Areaname, routes, State );StringThisnamespace = GetType (). namespace;If(Thisnamespace! =Null) {Context. namespaces. Add (thisnamespace +".*");} Registerarea (context );}

In createcontextandregister (...) CreateArearegistrationcontextAs a registerarea (...) The registerarea parameter isArearegistrationTo override the method in the inherited class. You only need to call the registerarea method.ArearegistrationcontextClass maproute (...) Method to complete the registration of a new route.

【Download Sample Code]

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

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.