Learning notes for ASP. net mvc 4 practice 9: routing (I ),

Source: Internet
Author: User
Tags actionlink

Learning notes for ASP. net mvc 4 practice 9: routing (I ),

In chapter 1 of this book, "security" is a relatively biased theory. It seems boring, so it should not affect the subsequent study... Okay, I want to be lazy...

1. URL routing introduction:

1. Default route:

When creating a new MVC 5 application, the default Project template creates a default route in the RouteConfig. cs file and registers the route in Global. asax:

Public class RouteConfig {public static void RegisterRoutes (RouteCollection routes) {routes. ignoreRoute ("{resource }. axd/{* pathInfo} "); // ignore route routes. mapRoute (name: "Default", // route name url: "{controller}/{action}/{id}", // parameter URL defaults: new {controller = "Home", action = "Index", id = UrlParameter. optional} // default value );}}
        protected void Application_Start()        {            AreaRegistration.RegisterAllAreas();            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);            RouteConfig.RegisterRoutes(RouteTable.Routes);            BundleConfig.RegisterBundles(BundleTable.Bundles);        }

2. inbound and outbound routes:

Inbound Routing: maps URLs to controllers or actions and any additional parameters;

Outbound Routing: constructs a URL that matches the URL scheme through the Controller, action, and any additional parameters.

Ii. design the URL scheme:
General principles for designing URL schemes:

  • Create simple and clean URLs;
  • Create a cracked URL;
  • Use URL parameters to differentiate requests;
  • Avoid exposing database IDS as much as possible;
  • Consider adding additional information.

Iii. Route implementation:

1. Online Store URL scheme:

2. Add custom static routes:
Route 1 and Route 2 are pure static routes:

            routes.MapRoute("home", "", new { controller = "Home", action = "Index" });            routes.MapRoute("privacy_policy", "privacy", new { controller = "Home", action = "Privacy" });

Note: The route order added to the route table determines the route search order for matching. This means that the routes listed in the source code should be reduced from the highest priority with the most specific conditions to the lowest priority or a fully-matched route.

3. Add a custom dynamic route:

Routing 3 and 4 are implemented using two routing parameters:

            routes.MapRoute("product", "products/{productCode}/{action}",                            new { controller = "Catalog", action = "Show" });

The productCode parameter in the preceding route is required, but action is optional, because the default value "Show" is provided for action in the subsequent anonymous type ".

Route 5 and 6:

            routes.MapRoute("catalog", "{action}",                            new { controller = "Catalog" },                            new { action = @"basket|checkout" });

These routes are almost static routes, but they are implemented using one parameter and one route constraint to maintain a small number of routes. There are two reasons for this: 1) Each request must scan the route table for matching, so a large route set will affect the performance; 2) the more routes, the higher the risk of routing priority problems.

4. Fully-matched routing:

We will add a fully-matched route to match any URL that has not been matched by other routes. This route aims to display the HTTP 404 error message. The global full-match route can match any URL, because it should be the last defined route:

            routes.MapRoute("404-catch-all", "{*catchall}", new { Controller = "Error", Action = "NotFound" });

The value catchall provides a name for the value to be picked up by the fully-matching route. Different from rule Routing Parameters, full match parameters capture the entire URL section, including the forward slash. In the preceding example, the route is mapped to the NotFound action of ErrorController:

namespace RoutingSample.Controllers{    public class ErrorController : Controller    {        public ActionResult NotFound()        {            return new NotFoundResult();        }    }}

NotFoundResult generates 404 custom action results:

namespace RoutingSample{    public class NotFoundResult : ActionResult    {        public override void ExecuteResult(ControllerContext context)        {            context.HttpContext.Response.StatusCode = 404;            new ViewResult() { ViewName = "NotFound" }.ExecuteResult(context);        }    }}

4. Use the routing system to generate a URL:

When a website requires a URL, the Framework automatically generates the URL Based on the routing rules instead of using a fixed URL string (hard-coded ). We need to specify a combination of controllers, actions, and parameters. The rest is done by the ActionLink method. ActionLink is an extension of the HtmlHelper class in the MVC framework. It generates a complete HTML <a> element, such:

@ Html. ActionLink ("MVC4 practice", "Show", "Catalog", new {productCode = "mvc-in-action"}, null)

Generation:

<A href = "/products/mvc-in-action"> MVC4 practice </a>

Sometimes we need to pass some additional parameters to the action, such:

@ Html. ActionLink ("MVC4 practice", "Show", "Catalog", new {productCode = "mvc-in-action", currency = "USD"}, null)

In this example, the currency parameter is passed. If this parameter matches a part of the route, it is called a part of the URL; otherwise, it will be appended to the query string. The link generated by the above Code is:

<A href = "/products/mvc-in-action? Currency = USD "> MVC4 practice </a>

If you want to request a specific route, you can use RouteLink, which accepts a parameter that identifies the route to be requested, such:

@ Html. RouteLink ("MVC4 practice", "product", new {productCode = "mvc-in-action"}, null)

This code searches for a route with the product name, instead of the specified controller and action.

If you need to get a URL, but not for a link or form (this usually happens when you write Ajax code and need to set a request URL ). The UrlHelper class can directly generate a URL, which is used by the ActionLink method or other methods, such:

@Url.Action("Show","Catalog",new{productCode="mvc-in-action"})

This code returns "/products/mvc-in-action", but there is no surrounding tag (that is, a simple URL ).

5. ASP. NET Web Form routing:

The preceding online store example assumes that there is a legacy page ProductByCategory. aspx originally written in ASP. NET Web Form, which lists products grouped by product category:

namespace RoutingSample{    public partial class ProductsByCategory : Page    {        private readonly ProductRepository _productRepository = new ProductRepository();        protected void Page_Load(object sender, EventArgs e)        {            string category=Request.QueryString["category"];             var productsByCategory = _productRepository.GetProductsByCategory(category);            _groupedProductsRepeater.DataSource = productsByCategory;            _groupedProductsRepeater.DataBind();        }    }}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ProductsByCategory.aspx.cs" Inherits="RoutingSample.ProductsByCategory" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

1. Add a route for the Web Form page:

            routes.MapPageRoute(                "ProductsByCategory",                "productsByCategory/{category}",                "~/ProductsByCategory.aspx",                checkPhysicalUrlAccess: true,                defaults: new RouteValueDictionary(new { category = "All" }));

2. Modify the Web Form to use RouteData:

Protected void Page_Load (object sender, EventArgs e) {// string category = Request. queryString ["category"]; string category = (string) RouteData. values ["category"]; // extract the value var productsByCategory = _ productRepository through the route data. getProductsByCategory (category); _ groupedProductsRepeater. dataSource = productsByCategory; _ groupedProductsRepeater. dataBind ();}

3. Generate a URL through the Web Form page:

We can use the routing infrastructure of the Web Form page to generate links to other routes, including links mapped to Controller actions. Modify page:

                                <asp:Repeater runat="server" DataSource='<%# Eval("Products") %>'>                                    <ItemTemplate>                                        <li>                                            <asp:HyperLink runat="server"                                                 NavigateUrl='<%# GetRouteUrl(new { controller="Catalog",action="Show",productCode=Eval("Code")})%>'                                                 Text='<%# Eval("Name") %>' />                                        </li>                                    </ItemTemplate>                                </asp:Repeater>

Call the GetRouteUrl method in the loop tag to bind its value to the NavigateUrl attribute of asp: Hyperlink. This method accepts an anonymous type and specifies the controller, action, and parameters to be linked.

Source code download password: onoy

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.