Deep understanding of ASP. NET MVC (3)

Source: Internet
Author: User
Tags actionlink

Series Catalogue

how URLs are generated through the routing table (outbound)

Usually we are recommended to use Html.ActionLink (...) in view design. The advantage of creating a link is that the URL can be generated based on the routing table. Another responsibility of the routing mechanism is to generate URLs based on the routing table, rather than manually written by us. Let's take a closer look at how it works.

A html.actionlink-like approach will eventually generate URLs by querying the routing table, and as with inbound, the routing tables are always sequentially traversed until they match . The GetVirtualPath method for each Route examines the method that accepts a routevaluedictionary parameter, which is actually provided by the appropriate helper. When the following three conditions are established, the match is considered successful:

Each parameter defined by a curly brace must be able to find the corresponding value. These values will have the following three sources in order of precedence:

1.the RouteValueDictionary parameter is explicitly provided. Which is what we provide when we invoke some helper that has the Generate URL function, such as the ActionLink method;

2.* from the routedata of the context of the current request; There is a more special case, which will be discussed in detail below;

3.the Defaults of the route.

Second, if the parameters in each defaults collection conform to the values in the routevaluedictionary parameter, and the values are not defined in the URL pattern with braces, then the match is considered. It sounds a bit awkward, here's an example.

If there are the following rules:

1234 routes.MapRoute( null,     "manage/orders/{page}",     new{ controller = "Admin",     action = "OrderManage", page = UrlParameter.Optional });

The page has the following links:

1 <ahref="<%:Url.Action("OrderManage", "Admin") %>">Order</a>

The last generated link will be like this (this omits the previous domain):

1 <ahref="…/manage/orders">Order</a>

There are two parameter controllers and actions in the Defaults , there are no similar {controller} and {action} in the pattern of the URL, The Url.action parameter also provides a parameter value that is consistent with the defaults setting (which is enough), so the URL is matched.

Three, each parameter conforms to the Constraints matching rule.

Once the above three conditions are met,GetVirtualPath will populate the URL with the corresponding parameters and eventually return the URL string. One thing to emphasize is thatthis behavior of the MVC framework works in lazy mode, and once the "need to be" is stopped, the traversal continues. This is also illustrated from another angle, putting the special forward on the golden principle.

As an example:

Here are two sequential route:

12345678910 routes.MapRoute(                null,                "manage/car",                new { controller = "Admin", action = "Car" }                );routes.MapRoute(                null,                "manage/car/{operation}",                new { controller = "Admin", action = "Car" }                );

There is a link that says:

1 <%: Html.ActionLink("Add Car", "Car","Admin", new{ operation = "add" }, null)%>

What is the final result? Is it manage/car/add?

In fact, the final result is manage/car, why? For the first route, it expects both the controller and the action parameters, and the above ActionLink does provide the two parameters completely, and is consistent with the defaults setting (which satisfies the second rule), so it matches! Even if the operation parameter is provided, the framework does not matter. This is obviously not a hope. Just change the location of the two route. This example is just a demo.

* The second point on condition one above is actually a great feature, here's an example:

Suppose the URL of the current page is:/catalog/list/purple/123

1 routes.MapRoute(null, "{controller}/{action}/{color}/{page}");
1 <%: Html.ActionLink("Click me", "List", "Catalog", new {page=789}, null) %>

Can this link match this route? Perhaps you think I did not provide a color parameter ah, how can match? In fact, the result is surprisingly:

1 <ahref="/Catalog/List/Purple/789">Click me</a>

Because the current page is/catalog/list/purple/123, the routedata in this case holds the color parameter value, although no setting color is displayed in ActionLink. However, the color parameter is still found in the current routedata.

Let's look at an example:

The URL of the current page is still:/catalog/list/purple/123

1 routes.MapRoute(null, "{controller}/{action}/{color}/{page}");
1 <%: Html.ActionLink("Click me", "List", "Catalog", new {color="Aqua"}, null) %>

Can this link still match this route? Perhaps you think that according to the above rules should be able, but the results are not matched, why? Because there is a principle,the data in the Routedata can only be used to populate the URL pattern in the "top parameter", the last parameter is not!

Finally, there is a principle of outbound that the value provided by defaults will not appear as far as the final URL results.

URL Design principles

In the framework of MVC, we can completely control the URL, and naturally think about how to design a good url,url. Because I have little experience in web development, the following is the contents of the book, I made some generalizations:

1.url should be as easy to understand as possible, do not include technical things in it, such as the following:

/website_v2/cachedcontentserver/fromcache/annualreport

/my%20great%20article (use/my-great-article as good)

2. Meaningful text is more comfortable than the ID number

3. Do not include a suffix in the URL

4. To have a relatively strong sense of hierarchy, but also short and easy to remember, such as:/products/menswear/shirts/red

5.url to be case insensitive, and to use lowercase letters as much as possible, the MVC framework is case-insensitive

6. Do not discard the old URL because of the change of the URL, the way to use the jump

7. Use the Get method for read-only operations, use post for requests to modify server data, and URLs to make it easier for people to save bookmarks or share Web pages, so the pagination is reflected in the URL for the page display

8.QueryString to use as little as possible. QueryString can be used when the parameter is to participate in an algorithm, rather than for direct resource pointing, because the user is not willing to enter the URL manually at this time. such as the page parameter

301 and 302

The same is to make the client browser jump,301 is a hint of permanent jump , can imply that the search engine this URL will be permanent, when the need for a more formal URL to consider;

302 represents a temporary jump , MVC's Redirecttorouteresult and Redirectresult use 302.

You can do the following 301 jumps like this:

12345678910111213141516171819202122 public static class PermanentRedirectionExtensions{    public static PermanentRedirectToRouteResult AsMovedPermanently        (this RedirectToRouteResult redirection)    {        return new PermanentRedirectToRouteResult(redirection);    }    public class PermanentRedirectToRouteResult : ActionResult    {        public RedirectToRouteResult Redirection { get; private set; }        public PermanentRedirectToRouteResult(RedirectToRouteResult redirection)        {            this.Redirection = redirection;        }        public override void ExecuteResult(ControllerContext context)        {            // After setting up a normal redirection, switch it to a 301            Redirection.ExecuteResult(context);            context.HttpContext.Response.StatusCode = 301;        }    }}
1234 publicActionResult MyActionMethod(){    returnRedirectToAction("AnotherAction").AsMovedPermanently();}

about SEO (search engine Optimization)

Tips for improving rankings:

1.url using keywords instead of numbers

2.url use less querystring, do not use underscores

3. Single content single URL, not multiple URLs pointing to the same content

4. If you want multiple URLs to point to the same content, use 301 to jump

5. The content of the Web page can be "addressed", to use the Get method, the content should not rely too much on post, or Js,flash,silverlight and other client technology.

Fruits of labor, reproduced please specify the source: http://www.cnblogs.com/P_Chou/archive/2010/11/08/details-asp-net-mvc-03.html

Deep understanding of 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.