Mvc3 custom class for Route configuration and URL generation

Source: Internet
Author: User

The routing configuration in MVC is directly related to the Controller and method of our request access. url plays an important role in Seo, it is not enough time to configure routes and generate URLs completely defined by MVC. This article will take a look at custom route configuration and URL generation.

1. routebase class Introduction

After creating a new MVC project, open the global file and you can see that route registration is implemented using a routecollection type parameter. When you press F12 to define it, you will find that it inherits the collection <routebase>. In addition to some maproute and other methods, there is also an add method whose signature is:

 
Public VoidAdd (StringName, routebase item );

It is actually a name for marking a route, and a routebase class. There are two methods corresponding to F12:

//When it is rewritten in a derived class, the request route information is returned.Public AbstractRoutedata getroutedata (httpcontextbase httpcontext );//When re-writing in a derived class, the system checks whether the route matches the specified value. If yes, a URL is generated and information about the route is retrieved.Public AbstractVirtualpathdata getvirtualpath (requestcontext, routevaluedictionary values );

The first method is to specify the controller and method through which the request is processed by processing the request information httpcontext. The second method is to specify the URL generated by the connection of the Request page. the following uses an example to describe the use of the above two methods.

Ii. routebase method 2.1 Requirement Description

to make the URL clearer, we use the following url: http: // www. ***. COM/category/LIST/page/n indicates the n-page list of a category. At the same time, the corresponding URLs of the previous pages and the next pages are respectively http: // www. ***. COM/category/LIST/page/n-1, http: // www. ***. COM/category/LIST/page/n + 1. The following uses the product category list page as an example, that is, http: // localhost: ***/product/LIST/page/n. Of course, there should be a better solution to this requirement, only to illustrate the use of routebase. For demonstration, we first create an MVC project, add a productcontroller In the controllers folder, and simply add a class table method:

PublicActionresult list (IntPage =1) {Viewbag. Count=Page; viewbag. Content="The"+ Page +"Page";ReturnView ();}

And add the corresponding view,

 @ {Viewbag. Title = "  List  " ;} <H2> product list </H2> <a href = "  @ URL. Action (  " Product "  ,  " List "  , New {page =  " Page "  , Id = convert. toint32 (viewbag. Count)-1 })  " > Previous page </a> <a href = " @ URL. Action (  " Product "  ,  " List "  , New {page =  " Page "  , Id = viewbag. Count })  " > @ Viewbag. content </a> <a href = "  @ URL. Action (  " Product " ,  " List "  , New {page =  " Page "  , Id = convert. toint32 (viewbag. Count) + 1 })  " > Next page </a>

Add a folder named infranstructure, create a class named myhelper, and inherit the routebase class,

2.2getroutedata usage

To configure the route, we do not use the maproute method. We can remove the default maproute in the Global File. We use the getroutedata method above, httpcontext is used to specify the methods in the Controller to process the request.CodeAs follows:

 Public   Class Myhelper: routebase {  Public   Override  Routedata getroutedata (httpcontextbase httpcontext ){  //  Specifies the route object for request processing as the mvcroutehandler object.              VaR Data = New Routedata ( This , New  Mvcroutehandler ());  //  The request URL is accepted, and the Controller, action, and action parameters are specified for the request.             String Strurl = Httpcontext. Request. rawurl;  String [] Arry = strurl. Split ( '  /  '  );  If (Arry. length> 4  ) {Data. Values. Add (  "  Controller  " , " Product  "  ); Data. Values. Add (  "  Action  " , "  List  "  ); Data. Values. Add (arry [  3 ], Arry [ 4  ]);  Return  Data ;} /*  If the URL does not meet the requirements, null is returned to match with other routes, and then the parameters of controller, action, and action are specified.  */              Return   Null  ;}  Public   Override  Virtualpathdata getvirtualpath (requestcontext, routevaluedictionary values) {// we will return a null 
 
Return Null;}
 
}

Because of the start time, maproute is removed. Now we need to use the add method, so add

Routes. Add (NewMyhelper ());

Run nowProgramAnd enter http: // localhost: 3519/product/LIST/page/1 in the address bar, as shown below:

At this time, the request has taken effect through our custom route, but we found that the connection between the previous page and the next page is not what we want. If we want to meet our requirements, then we need to use the getvirtualpath method to generate a specified URL for the connection to the request page.

2.3 use of getvirtualpath

If you don't talk much about it, paste the Code. For some instructions, see the notes:

 ///   <Summary>          ///  Generate a specific URL for the specified request page  ///   </Summary>          ///   <Param name = "requestcontext">  Request page </Param>          ///   <Param name = "values">  Auxiliary classes such as HTML. action on the request page  </Param>          ///   <Returns> </returns>          Public   Override  Virtualpathdata getvirtualpath (requestcontext, routevaluedictionary values ){  //  First, determine whether the request meets the requirements. The request action is list and the page cannot be blank.              If (Requestcontext. routedata. Values ["  Action  " ]. Tostring () = "  List  " &&! String . Isnullorempty (requestcontext. routedata. Values [ "  Page  "  ]. Tostring ())){  //  Define a URL string                  String Strurl =String  . Empty;  //  If there are four values in values, perform the following operations:                  If (Values. Count = 4  ){  If (Convert. toint32 (Values [ "  ID  " ])> = 1  ) {Strurl = Values [ " Controller  " ]. Tostring () + "  /  " + Values [ "  Action  " ]. Tostring () + "  /  " + Values [ "  Page  " ]. Tostring () + "  / " + Values [ "  ID  "  ]. Tostring ();}  Else  {Strurl = Values [ "  Controller  " ]. Tostring () + "  /  " + Values [ " Action  " ]. Tostring () + "  /  " + Values [ "  Page  " ]. Tostring () + "  /1 #  "  ;}  Return   New Virtualpathdata ( This , Strurl );}}  Return   Null  ;} 

Now we want to run the http: // localhost: 3519/product/LIST/page/1 page.

Note: The time for judging the two methods above must be accurate. Otherwise, it may be specified to the wrong controller and method and the wrong URL. In addition, if it does not meet the specified requirements, return NULL to use other routing configurations.

Iii. Summary

This article describes how to generate custom routes and URLs through a paging instance. The example may be poor, but it is easy to understand. Source code.

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.