Routing in ASP. NET MVC 3

Source: Internet
Author: User
Tags null null actionlink

Ready to release a new essay, only to find the draft in a few years ago this piece of rotten tail, first put up, have time to fill the complete bar ...

(* Organize your learning notes from the Pro ASP. NET MVC 3 Framework.) *)

Routing, as its name is, is the process of determining where messages are passed to. As well as the network device router router, the ASP. NET MVC framework processes the request URL in a way that relies on a predefined routing table. With this routing table as the forwarding basis, the request URL is eventually passed to the specific action of the specific controller for processing. In the opposite direction, the MVC Framework renderer also uses this routing table to generate the final HTML page and return the URL. So, to understand the entire routing system, there are two key elements that must appear: the controller and the action, there are two directions: the incoming path resolution and the outgoing path generation.

One, routing parsing
A URL consists of three parts:
Http://www.website.com/Admin/Index
Protocol Host query string

Route parsing is the process of passing a fragment of Admin/index to the appropriate controller's action. As for routing, it relies on the preset routing table entries for guidance. So, before everything starts, you need to complete the routing table configuration by adding a route entry.

The addition of a route item is implemented by the Routecollection.maproute () or Routecollection.add () method and is typically used in the RegisterRoutes () method in the MVC project portal Global.asax. Among them, MapRoute () is more common and direct.

MapRoute (String routeName,//name of the route item, used for path pattern matching
String Urlpattern,//Path mode
Object defaultproperties,//path element with default value for parameter
The constraint for this route item applies when the object constraints,//conditions are met
String[] namespaces)//define the namespace of the controller location

In other words, the end result of the route is to get the three items of controller.action (parameters). These three items will appear in the defaultproperties of Maproute (). Defaultproperties is an object of an anonymous class whose properties include the controller name, the action name, and other parameters.

Routes. MapRoute ("Routea",
"{Controller}/{action}/{page}",
New {controller = "Admin", action = "Index", page = 1})

As in the example above, the 2nd parameter urlpattern the corresponding pattern string, and {} The enclosing part is a placeholder, similar to string. Format pattern string in format (). The entire pattern string, used to match the entire contents of the host name in the URL. The element corresponding to the placeholder is then fully present in the defaultproperties, which is mapped to the corresponding property.

When you match URLs with Urlpattern, they match exactly like the method's parameter table. The default value provided in Defaultproperties is automatically used for items that are not provided for the request URL. Finally, the result of the match is to pass the request to a method like this, the controller name, the action name, and the parameter name page of the anonymous class as the property are strictly matched to the actual method prototype (the match ignores the case of the name).

public class Somecontroller
{
Public ViewResult someaction (int page) {...}
}

URLs with too many placeholder fragments are mismatch. As the following table:

URL Controller Action Page
Http://www.website.com/Admin Index 1
Http://www.website.com/Product Product Index 1
Http://www.website.com/Admin/Index Admin Index 1
Http://www.website.com/Admin/Logon Admin Logon 1
Http://www.website.com/Product/List Product List 1
HTTP://WWW.WEBSITE.COM/ADMIN/INDEX/5 Admin Index 5
Http://www.website.com/Admin/Index/5/detail null NULL NULL

Second, the Order of routing table entries directly affects the routing results. Because the MVC framework matches the order in which route items are added, rather than the level of matching, the more special route items need to be defined earlier. Inverse URL pattern, it will be strictly according to the semantics of the format string parsing. such as "Prefix/{controller}/{action}", will match to a URL like Http://www.website.com/Prefix/Product/List ". If the URL points to a specific file, such as "download/somefile.pdf", you can also set routecollection.routeexistfiles = True so that the file is also taken over by the routing system. Passed to a specific controller.

In addition to the above way of specifying parameter defaults in a route, you can also use urlparameter.optional to declare optional parameters to affect routing. The default parameter in the route definition will always be different, and an optional parameter means that only the fragment corresponding to the optional parameter in the request URL will be constructed and passed to the action, otherwise the parameter is never defined and exists.

Routes. MapRoute ("Routea",
"{Controller}/{action}/{page}",
New {controller = "Admin", action = "Index", page = urlparameter.optional})

For the optional parameter page in the previous example, you can specify its default value when you define an action. If you look at the default value, the default parameter is very similar to the optional parameter, but the optional parameter is not a fixed existence for the action.

public class Admincontroller
{
Public ViewResult Index (int page = 5) {...}
}

In addition, there are variable-length route variables, similar to the variable-length method parameters defined with the params keyword. Specifically, precede the placeholder name with *, just like {*arguments}. The routing framework then matches the URL segment by path pattern and passes all fragments of the end mismatch as a/delimited string to the parameter arguments. Within the action, you can split and parse the arguments to make other processing that you need.

Next, is the namespace in the route item that determines the namespace that the route item can refer to when it finds the controller. MVC will first look for the controller in the namespace given by the parameter, and the lookup does not go to other namespaces it can reach. You can force a lookup only in the specified space by setting the datatokens["usenamespacefallback" = False of the route entry.

The namespace given by the namespaces parameter, regardless of its order, has a controller with equal precedence. If there is a controller with the same name in different spaces, it will directly result in a conflict of the same name. To avoid conflicts, you can define different route entries for the namespace of these conflicting controllers, and give appropriate consideration to which route items are placed earlier.

Finally, there is a slightly more complex parameter, constraints, which determines the conditions that the route entry applies to. The relationship between some conditions, for and, must be met at the same time. Constraints can be used simply to make use of regular matches, as follows: This route entry applies only if the controller name starts with H and the action is index or about.

MapRoute ("Myroute",
"{controller}/{action}/{id}/{*arguments}",

New {controller = "Home", action = "Index", id = urlparameter.optional},

New {controller = "^h.*", action = "^index$|^about$"},

New[] {"Somenamespace.controllers"});

More complex constraints are provided by implementing the constraint object of the Irouteconstraint interface, which focuses on implementing the bool Match () method in the interface. You can then filter the browser kernel by simply adding a section of Ieconstraint = new Agentieconstraint () to the constraint table above.

public class Agentieconstraint:irouteconstraint

{

public bool Match (httpcontextbase context, Route route, string name, routevaluedictionary values, Routedirection directio N

{

Return (context. Request.useragent = null)

&& (context. Request.UserAgent.Contains ("IE");

}

}

Second, the output URL

Another important feature of the routing system is the generation of URLs. This is achieved mainly through Html.ActionLink (), Html.routelink (), Url.action (), Url.routeurl (), and so on, they are equivalent, the parameters are approximate, and ActionLink () is generated <a > tags point to specific actions more commonly, routelink () can directly select specific routes and point to specific files, folders and other resources.

ActionLink (string text,//link Display

String action,//action name

String controller,//controller name

String protocol,//url protocol, such as "http" or "https"

String host, hostname in//url

String fragment,//url fragment name (anchor name)

Object Routevalues,//One containing the route parameters

Object Htmlattributes//An object that contains the HTML attributes to set for the element

)

Routing in ASP. NET MVC 3

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.