Step by step learn to use URL Routing in ASP. NET 4 WEB applications)

Source: Internet
Author: User
Document directory
  • Create a route
  • Create a hyperlink using a route
  • Access URL parameter values on the ASP. NET page
  • Test route
Create a route

A route map a URL path to a specific physical file. To add Routes to a website, use the RouteCollection. MapPageRoute method to add them to the static Routes attribute of the RouteTable class.

Add the method used to add a route to the Global. asax file.
  1. If the website does not have the Global. asax file, add one by performing the following steps:

    1. Right-click the Web Project in Solution Explorer and select Add new project ".

    2. Select Global Application class and click Add ".

  2. Open the Global. asax file.

  3. Add the Import command for the System. Web. Routing namespace after the Application Command, as shown in the following example:

    <%@ Import Namespace="System.Web.Routing" %>
  4. Add the following code after the Session_End method:

    Void RegisterRoutes (RouteCollection routes)
    {
    }

    In the following process, you will add the code for creating a route to this method.

  5. In the Application_Start method, call RegisterRoutes to add routing rules, as shown in the following example:

Void Application_Start (object sender, EventArgs e)
{
RegisterRoutes (RouteTable. Routes );
}

The preceding process adds an empty Method for registering a route. Now, we will use this method to add the route to the website.

Add route
  1. In the RegisterRoutes method, add the following code:

    Routes. MapPageRoute ("",
    "SalesReportSummary/{year }",
    "~ /Sales. aspx ");

    This Code adds an unnamed route that has a URL matching mode that contains the text value "SalesReportSummary" and a placeholder named year (URL parameter ). It maps the route to a file named Sales. aspx.

  2. In the RegisterRoutes method, add the following code:

    Routes. MapPageRoute ("SalesRoute ",
    "SalesReport/{locale}/{year }",
    "~ /Sales. aspx ");

    This Code adds a route named SalesRoute. If you name the routing rules, you can use the same name to distinguish them when creating the same routing rules below.

  3. In the RegisterRoutes method, add the following code:

    Routes. MapPageRoute ("ExpensesRoute ",
    "ExpenseReport/{locale}/{year}/{* extrainfo }",
    "~ /Expenses. aspx ", true,
    New RouteValueDictionary {
    {"Locale", "US "},
    {"Year", DateTime. Now. Year. ToString ()}},
    New RouteValueDictionary {
    {"Locale", "[a-z] {2 }"},
    {"Year", @ "\ d {4 }"}});

    This Code adds a route named ExpensesRoute. This route includes a common matching parameter extrainfo. This Code sets the default value of the locale parameter to "US" and the default value of the year parameter to this year. The specified locale parameter must consist of two letters. The year parameter must consist of four digits.

Create a hyperlink using a route

When adding a hyperlink to a webpage, if you want to specify a route URL instead of a physical file, you have two options:

  • The routing URL can be hard-coded.

  • You can specify the route parameter name and value, and have ASP. NET generate the corresponding URL. If necessary, you can also specify the route name to uniquely identify the route. If you change the routing URL rules later, you must update all hard-coded URLs. NET to generate a URL, the correct URL is always automatically generated (unless the parameters in the mode have been changed ).

In the following process, add a hyperlink using a hardcoded URL to a webpage.

Create a hard-coded URL
  1. In "Solution", right-click the Web Project and click "Add Item ".

    The "Add Item" dialog box is displayed.

  2. Select the "Web form" template, ensure that "Place code in separate file" is selected, set the name to "Links. aspx", and click "add ".

    The Links. aspx page is displayed in the "Source" view.

  3. Add the following tag between the start and end <div> tags:

    <Asp: HyperLink ID = "HyperLink1" runat = "server"
    NavigateUrl = "~ /Salesreportsummary/2010 ">
    Sales Report-All locales 2010
    </Asp: HyperLink>
    <Br/>
    <Asp: HyperLink ID = "HyperLink2" runat = "server"
    NavigateUrl = "~ /Salesreport/WA/2011 ">
    Sales reports-WA, 2011
    </Asp: HyperLink>
    <Br/>
    <Asp: HyperLink ID = "HyperLink3" runat = "server"
    NavigateUrl = "~ /Expensereport ">
    Expense Report-Default Locale and Year (US, current year)
    </Asp: HyperLink>
    <Br/>

    This tag uses a hardcoded URL to create three HyperLink controls. The first hyperlink matches the URL mode of the sales summary route, the second hyperlink matches the Route named SalesRoute, and the third hyperlink matches the Route named ExpensesRoute. Because no parameter is specified for the URL of the third hyperlink, the default value defined for this route will be passed to Expenses. aspx.

Next, add tags (these tags create hyperlinks used to specify route parameters and Route names) to create a route URL.

Use tags to create automatically generated URLs
  • Keep Links. aspx open in the "Source" view. Add the following code after creating the HyperLink control in the previous process:

    <Asp: HyperLink ID = "HyperLink4" runat = "server"
    NavigateUrl = "<% $ RouteUrl: year = 2011%>">
    Sales Report-All locales 2011
    </Asp: HyperLink>
    <Br/>
    <Asp: HyperLink ID = "HyperLink5" runat = "server"
    NavigateUrl = "<% $ RouteUrl: locale = CA, year = 2009, routename = salesroute %>">
    Sales Report-CA, 2009
    </Asp: HyperLink>
    <Br/>

    This tag uses the RouteUrl expression to create a URL named SalesSummaryRoute and SalesRoute. The second RouteUrl expression specifies the route name, because the list of parameters provided in the Code can match ExpensesRoute URL mode or SalesRoute URL mode. The ExpensesRoute URL mode has the extrainfo placeholder not available in the SalesRoute URL mode, but extrainfo is a placeholder that can be used to place various information, which means it is optional.

In the following process, you will add a tag for creating a hyperlink, and use the code to generate a hyperlink URL by specifying the route parameters and route name.

Use code to create automatically generated URLs
  1. Keep Links. aspx open in the "Source" view. Add the following code after creating the HyperLink control in the previous process:

    <Asp: HyperLink ID = "HyperLink6" runat = "server">
    Expense Report-CA, 2008
    </Asp: HyperLink>
    <Br/>

    This flag does not set the NavigateUrl attribute because it will be generated when the code is running.

  2. In "Solution", expand Links. aspx and then enable or Links. aspx. cs.

  3. Add the using statement to the System. Web. Routing namespace, as shown in the following example:

    using System.Web.Routing;
  4. In the Page_Load method, add the following code:


    This Code creates a RouteValueDictionary class with three parameters. The third parameter is category, which is not in URL mode. Because it is not in URL mode, the category parameter and its value are displayed as the query string parameter.

  5. Add the following code after the code added in the previous step:

    VirtualPathData vpd =
    RouteTable. Routes. GetVirtualPath (null, "ExpensesRoute", parameters );

    This code instantiate the VirtualPathData object by calling the GetVirtualPath method of the RouteCollection class. Because the SalesRoute URL mode and ExpensesRoute URL mode have similar placeholders, it calls an overload that accepts the route name and specifies the ExpensesRoute value.

  6. After the code added in the previous step, add the following code to set the NavigateUrl attribute of the hyperlink:

    HyperLink6.NavigateUrl = vpd.VirtualPath;
Access URL parameter values on the ASP. NET page

On ASP. NET pages that have been called by ASP. NET routes, you can search URL parameter values in tags or codes. For example, the SalesReport route includes parameters named locale and year. When you receive a URL request that matches this mode, the code on the Sales. aspx page may need to pass the values of these parameters to the SQL query.

In the following process, the access URL parameter value is marked. This method can be used to display parameter values on a webpage.

Access URL parameter values with tags
  1. Right-click the Web Project and click "Add new project ".

    The "Add new item" dialog box is displayed.

  2. Select a Web form template and set the name to "Expenses. aspx ".

    The Expenses. aspx page is displayed in the "Source" view.

  3. Add the following tag between the start and end <div> tags:

    <H1>
    Expense Report
    <Asp: Literal ID = "Literal1"
    Text = "<% $ RouteValue: locale %>"
    Runat = "server"> </asp: Literal>,
    <Asp: Literal ID = "Literal"
    Text = "<% $ RouteValue: year %>"
    Runat = "server"> </asp: Literal>
    </H1>

    This tag is extracted using the RouteValue expression and displays the value of the URL parameter passed to the page.

The following process uses the code to access the parameter value. This method is useful when you have to process data in some way (for example, by converting the null value to the default value as shown in this process, or by passing the information to an SQL query.

Use code to access URL parameter values
  1. Right-click the Web Project and click "Add New Item ".

    The New Item dialog box is displayed.

  2. Select the "Web form" template, make sure to select "put code in a separate file", set the name to "Sales. aspx", and then click "add ".

    The Sales. aspx page is displayed in the "Source" view.

  3. Add the following tag between the start and end <div> tags:

    <H1>
    Sales Report
    <Asp: Literal ID = "LocaleLiteral" runat = "server"> </asp: Literal>,
    <Asp: Literal ID = "YearLiteral" runat = "server"> </asp: Literal>
    </H1>

    This flag includes the Literal control, but does not set its Text attributes, because these attributes will be set in the code.

  4. In "Solution", expand Sales. aspx and then open Sales. aspx. cs.

  5. In the Page_Load method, add the following code to set the Text attribute of the first Literal control to one of the following values:

    • The text "All region Settings" (if the locale parameter is null ).

    • The value of the locale parameter (if the locale parameter is not null ).

      LocaleLiteral.Text = Page.RouteData.Values["locale"] == null ?
      "All locales" : Page.RouteData.Values["locale"].ToString();
  6. In the Page_Load method, add the following code to set the Text attribute of the first Literal control to the value of the year URL parameter:

    YearLiteral.Text = Page.RouteData.Values["year"].ToString();
Test route

Now you can test the route.

Test route
  1. In Solution Explorer, right-click Links. aspx and select View in browser ".

    This page is displayed in the browser, as shown in:

  2. Click each hyperlink.

    Note that each hyperlink is directed to a page whose title corresponds to the text of the hyperlink.

  3. Return to the Links. aspx page, select the "View Source" command in the browser, and check the URL of the last three hyperlinks.

    You will see the following automatically generated URL:

    • Http: // [server]/[application]/SalesReportSummary/2011

    • Http: // [server]/[application]/SalesReport/CA/2009

    • Http: // [server]/[application]/ExpenseReport/CA/2008? Category = recreation

  4. Copy the URL Ending with SalesReport/CA/2009 to the Windows clipboard and close the "View Source" window.

  5. Paste the URL into the address bar of the browser, change CA to "invalidlocale", 2009 to "invalidyear", and then press Enter.

    A page similar to the following is displayed:

    You can see the sales report page showing invalidlocale and invalidyear values. Because no constraint is specified for the SalesRoute route, invalid data is accepted.

  6. Paste the URL to the address bar of the browser again, change CA to "invalidlocale", 2009 to "invalidyear", SalesReport to "ExpenseReport", and press Enter.

    A page similar to the following is displayed:

    Because the URL is not resolved as a route, you will see the "not found" error. The ExpenseReport route will only accept the locale parameter with two letters and the year parameter with four digits.

Original article link

Additional reading

ASP. NET 4 new features (1) Core ASP. NET services

ASP. NET 4 new features (2) ASP. NET Web forms enhancements

ASP. NET 4 new features (3) enhanced Web Standard Support and auxiliary functions

ASP. NET 4 new features (4) other new features and VS 2010 support for ASP. NET 4 (complete)

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.