Introduction to MVC Routing

Source: Internet
Author: User

When we create an ASP. NET MVC Web program, a Global.asax file is generated. As follows:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 usingSYSTEM.WEB.MVC;6 usingSystem.Web.Routing;7 8 namespacekkx9 {Ten     //Note: For instructions on enabling IIS6 or IIS7 Classic mode, One     //please visithttp://go.microsoft.com/?LinkId=9394801 A  -      Public classMvcApplication:System.Web.HttpApplication -     { the          Public Static voidregisterglobalfilters (globalfiltercollection filters) -         { -Filters. ADD (NewHandleerrorattribute ()); -         } +  -          Public Static voidregisterroutes (routecollection routes) +         { ARoutes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); at  - routes. MapRoute ( -                 "Default",//Route name -                 "{Controller}/{action}/{id}",//URL with Parameters -                 New{controller ="Home", action ="Index", id = urlparameter.optional}//parameter Default value -             ); in  -         } to  +         protected voidApplication_Start () -         { the Arearegistration.registerallareas (); *  $ registerglobalfilters (globalfilters.filters);Panax Notoginseng registerroutes (routetable.routes); -         } the     } +}
View Code

Application_Start () is the portal when the Web application starts.

The registerglobalfilters () method is used to register the global filter, which is not related to the content of this article.

The registerroutes () method is used to register the routing table.

Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

Ignoreroute () is an extension method for the routecollection routing table class that ignores the specified routing request. This means ignoring requests that have an. axd file extension.

  routes. MapRoute (  default   ", //  route name   " {controller}/{action}/{id}  "  , //  URL with parameters  new  {controller =  " home   ", action = "  index   ", id = urlparameter.optional} //  parameter default value /span>); 

MapRoute () is a way to add a route map (an extension method ofroutecollection ), which is one of his most common overloads, mapping the specified URL route and setting the default route value:

1. "Default" is the name of the route, which is unique in the collection of routes for the application (the Routes object) and will be an error if the duplicate name is generated.

2. ' {controller}/{action}/{id} ' represents a URL expression for a route.

3. New {controller = "Home", action = "Index", id = urlparameter.optional} declares an object anonymous with the route value /c10>. This statement adds a routing rule that maps the URL expression to a route value-pointing to an action method under a controller.

When publishing a Web site, the Global.asax file is compiled into a DLL. When the program starts, it calls the Application_Start () method First,

After the RegisterRoutes (routetable.routes) statement is executed, the routing table is registered and the default routing rule takes effect.

With this default rule, we can use/controllername/actionname?querystring= ... Such a relative URL to invoke each action method in the program.

How to define a URL expression:

First, the URL expression is relative , not including the host domain name part (such as http://www.xxx.com). {} the placeholder is saved,"/", "." It is used as a delimiter, and nothing is static content:

    • url/category/showcategory/1000 matches "{Controller}/{action}/{id}".
    • Url/product/2012/4/28.html matches the "/product/{year}/{month}/{day}.html", and so forth.

It is important to note that {Controller} and {action} are two reserved placeholders, each representing the corresponding controller name and operation name.

The name of the controller (s), which is defined as the controller suffix, is removed, Categorycontroller is category

{action} corresponds to the name of the action method within the controller.

There are two different kinds of operations for routing:

  gets the route value , when you enter a URL in the browser, the program will match the URL expression in the route table we added to find the corresponding route value.

Let's take a look at an example and we'll add two routing rules.

Routes. MapRoute ("Test","where-are-you-going",New{controller ="Home", action ="Index"}); routes. MapRoute ("Test1","where-are-you-going",New{controller ="Home", action ="Others"});

Suppose there are two actions in HomeController that are Index () and Others () respectively.

Do you think which method will be called in the browser input http://www.xxx.com/where-are-you-going ? What if it's upside down?

< call Homecontroller.index ()/Call homecontroller.othersafter reverse >

  To get the URL, the following code uses the url.action method to fully qualify a URL using the Controller and the Action name.

That is, we have a route value, by matching in the routing table, we can find the corresponding URL pattern, and then generate a URL

<a href="@Url. Action ("Index""Home") "> Home </a>

Now let's add one of the following routing rules under the default routing rules

Routes. MapRoute ("myhome""myhome/{id}"new"  Home""Index", id = urlparameter.optional});

The above questions you can try it yourself, it is clear that the route matching is top-down , as long as the match to the first record, will return the corresponding URL or route value. This is very important. Many people always find that their rules do not take effect when they customize routing rules. Then you should check if it was overwritten by the previous route.

From the URL of this station can be seen, http://www.xxx.com/category/showcategory?categoryid=1000&view=list&orderby=price&page =1, it should only be a default routing rule,

You can infer that there is a controller named category, which has a method named Showcategory, the required parameter is CategoryID, and the other is an optional parameter.

Routes. MapRoute ("Category""Category/{categoryid}"new " Category " " showcategory " }

This time must pay attention to Oh, do not write in the default route below, you understand. Or you're going to be a tragedy.

In general, we recommend that if you need to use the Globel file to customize the route, delete the original default route and customize your own route for each action.

Introduction to MVC Routing

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.