Study Notes on Pro ASP. net mvc 3 framework [url and routing]

Source: Internet
Author: User
Tags actionlink

Create an outgoing URL (outgoing URLs)

Processing incoming URLs is only a part of the routing system. We also need to use the URL architecture to create outgoing URLs. We can embed these URLs into our view and allow users to click the URL to submit the form to our application, and can hit the appropriate controller and action.

Different technologies are used to create outgoing urls:

The most convenient way to create an outgoing URLs is to manually define a URL such as <a href = "/home/about"> about this application </a>. This URL will hit the about action method in homecontroller. Manually defining outgoing URLs is indeed very convenient, but it is also very dangerous, because once you change the URL architecture of your application, you will break all the manually created outgoing URLs. You must check and modify the outgoing URLs in all views and update references to these URLs in all controllers and actions.

The routing system can create a URL from the URL architecture. Therefore, if the URL architecture changes, the outgoing URLs created in the view will also change. Obviously, this method is wise, but we also need to do some initialization work in the early stage. This is very worthwhile. In the long run, this will benefit us a lot.

The following example shows that the previous project is still used,

Only make some modifications: 1) Remove additionalcontrollers 2) Modify registerroutes as follows:

View code

public static void RegisterRoutes(RouteCollection routes) 
{
routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

The easiest way to create an outgoing URL in the view is to call the HTML. actionlink method. For example, @ HTML. actionlink ("about", "about "). this method creates a URL based on the current URL architecture. You can view the source file on the page and find that the URL is <a href = "/home/about"> about </a>. Suppose we change the URL architecture as follows:

View code

public static void RegisterRoutes(RouteCollection routes) 
{
routes.MapRoute("NewRoute", "App/Do{action}",
new { controller = "Home" });

routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

We will get a URL like this: <a href = "/APP/doabout"> about </a>

Understanding output URL route matching

Through the above introduction, we have learned how the routing system creates an outgoing URL Based on the URL architecture change. Applications usually define several routes, so it is very important to understand how a route is selected for URL creation. The routing system processes the route according to the order in which the route is added to the routecollection. The routecollection object is to be passed to the registerroutes method. Check whether a route is matched based on the following three conditions:

1) The provided value must be available for each segment variable defined in the URL mode.
Follow the following rules when searching for values for each segment:
First, the routing system will search for the value we provide, that is, the value defined in the anonymous type attribute.
Second, search
Finally, find the default value provided when we define the route

2) The segment variable values we provide may be consistent with the default-only variable defined in the route. The default values of these variables are provided, but these variables are not included in our defined URL mode.
For example, there is a route: routes. maproute ("myroute", "{controller}/{action}", new {myvar = "true"}); among them, myvar is the default-only variable. to match this route,
Do not provide a value for myvar or make sure that the value we provide matches the default value.

3) The value of all segment variables must meet the routing constraints.

It should be clear that the routing system is not looking for the best matching route, but just looking for the first matching and then using it to create a URL. Only when a matched route is found, the routing system will ignore all the later routes. Therefore, when we define a route, we must follow the specific to Fuzzy Order.

The following is a unit test of outgoing URLs.

View code

[TestMethod] 
public void TestOutgoingRoutes()
{
// Arrange
RouteCollection routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
RequestContext context = new RequestContext(CreateHttpContext(), new RouteData());

// Act - generate the URL
string result = UrlHelper.GenerateUrl(null, "Index", "Home", null,
routes, context, true);

// Assert
Assert.AreEqual("/", result);
}

Target other controllers (targeting other controllers)

By default, the actionlink method assumes that we are targeting the Action Method in the same controller. This action method is used to present the view. If you want to specify other controllers, you can add more parameters, such as @ html. actionlink ("about this application", "about", "mycontroller ").

Pass an additional value (passing extra values)

You can use an anonymous attribute to pass the value of the segment variable. For example, @ html. actionlink ("about this application", "about", new {id = "myid "}). The generated URL is as follows:
<A href = "/home/about/myid"> about this application </a>

Understand the reuse of segment Variables

When we describe that the route matches the outgoing URLs, we mention that when we look for a value for each segment variable, the routing system will look for it from the current request. Now we define a route as follows:
Routes. maproute ("myroute", "{controller}/{action}/{color}/{page }")

Then define a connection in the index view: @ HTML. actionlink ("Click me", "Index", "home", new {page = 789}, null ). to run the program, enter the following URL:
Http: // localhost: <port>/home/index/Purple/123. The link displayed on the page is: <a href = "/home/index/Purple/789 "> click me </a>.

We didn't assign a value to the color when defining the link. How does the purple come from here?

This is to reuse the URL: http: // localhost: <port>/home/index/PurpleThe color value in/123 is purple. In addition, the routing system re-uses the value of the segment variable before the page. When we modify actionlink: @ html. actionlink ("Click me", "list", "catalog", new {color = "Aqua"}, null );

Here we provide the color value. Because color is before page, the color value of the imported URL will not be reused here. Displayed as: <a href = "/? Color = Red "> click me </a>
We strongly recommend that you avoid this kind of behavior, but provide the values of all the segment variables you need when defining the URL mode.
When the value we provide is inconsistent with the value of the segment variable, this value will be appended to the URL as querystring.

For example, @ html. actionlink ("about this application", "about", new {id = "myid", myvariable = "myvalue"}), The created connection is shown as follows:
<A href = "/home/about/myid? Myvariable = myvalue "> about this application </a>.

If the value we provide happens to be the same as the default value, the routing system will ignore the variable from the outgoing URL. For example, create a link @ html. actionlink ("about this application", "Index", "home "). The displayed link is as follows: <a href = "/"> about this application </a>

Specify HTML attributes

You can specify a CSS style for the created link. For example, you can specify a style category as mycssclass. You can do this:
@ Html. actionlink ("about this application", "Index", "home", null, new {id = "myanchorid ",@Class = "mycssclass"}) Note that a "@" symbol is used here, because class is a keyword in C #, here the HTML style class name is required. As shown in the following figure, the <A> tag has one more attribute: <Class = "mycssclass"Href = "/" id = "myanchorid"> about this application </a>

Create an absolute path URL

The previous steps are relative paths. We can also create full paths as follows:

@ Html. actionlink ("about this application", "Index", "home", "HTTPS", "myserver.mydomain.com ",
"Myfragmentname", new {id = "myid"}, new {id = "myanchorid", @ class = "mycssclass "}).

We recommend that you use relative paths as much as possible. Because the full path depends on the infrastructure of the applications presented to users, large applications that rely too much on the absolute path are finally damaged due to changes in network infrastructure or domain name policies, this change is often beyond the control of programmers.

Sometimes we need to display the URL as text on the page. This can be URL. Action (), which is similar to HTML. actionlink.

Create a link or URL Based on Routing Data

For example, @ html. routelink ("routed link", new {controller = "home", Action = "about", id = "myid "}).

The link displayed on the page is as follows:
<A href = "/home/about/myid"> routed link </a>

You can use the URL. routeurl method to display the created link in text.

Create outgoing URLs in the Action Method

In most cases, we will create outgoing URLs in the view.,But sometimes we also need to do something similar in the Action method. The method is the same, as shown below:

View code

        public ActionResult MyActionMethod()
{
string myActionUrl = Url.Action("Index", new { id = "MyId" });
string myRouteUrl = Url.RouteUrl(new { controller = "Home", action = "About" });
return Redirect(myRouteUrl);
}

Create a URL based on a specific route

When we use routes. maproute (), we generally use a name as a parameter, as shown below:

Routes. maproute ("myroute", "{controller}/{action }");
Routes. maproute ("myotherroute", "app/{action}", new {controller = "home "});

There are two reasons for naming route:

1. Can be used to prompt the role of this route 2. You can select a specific route when creating an outgoing URL

When we use @ html. actionlink ("Click me", "about"), which route will we select?

The answer is: the first route defined in registerroutes. Here myroute is selected. Of course, you can also specify a route by yourself, such as @ html. routelink ("Click me", "myotherroute", new {Action = "about "});

Naming routing is not recommended.

Creating outgoing URL-dependent route naming breaks the "decomposition Focus" (this is the core idea of the MVC design pattern ). When creating a URL or link in a view or action, we focus on the action and controller to which the user will be directed, rather than the URL format to be used. SoWe tend to avoid naming route, but use null instead..

Now, let's take the note of today!
Have a good weekend!

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.