15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

outing ❘ 1249<br />

If you have two routes that map to the same URL, you may want to determine which route was matched. To<br />

do so, you can include additional data that is passed to the page as a data token. Data tokens are supplied<br />

with another RouteValueDictionary collection, containing a collection of name/value pairs of route<br />

parameters <strong>and</strong> data tokens. For example:<br />

RouteTable.Routes.Add("RouteName",<br />

new Route("path/{pathparameter}",<br />

new RouteValueDictionary<br />

{<br />

{ "pathparameter", "yes" }<br />

},<br />

new RouteValueDictionary<br />

{<br />

{ "pathparameter", "yes|no" }<br />

},<br />

new RouteValueDictionary<br />

{<br />

{ "customdatatoken", "yesnomatch" }<br />

},<br />

new PageRouteH<strong>and</strong>ler("~/target.aspx")));<br />

If this route is matched a data token called customdatatoken with a string value of yesnomatch is passed<br />

to the target URL, so that pages can identify that this route was used.<br />

You can pass whatever data you like as a data token for a parameter, so this is only one example of how you<br />

might use it.<br />

using route Parameters<br />

Reading <strong>and</strong> using parameter values that are passed to pages through ASP.<strong>NET</strong> routing is very similar<br />

to doing the same for query string parameters. Instead of using Request.QueryString, you use Page<br />

.RouteData, which is populated by ASP.<strong>NET</strong> when your page is loaded. This contains all of the<br />

information you need to extract route parameters or data tokens.<br />

Parameter values are also available for use in ASP.<strong>NET</strong> markup, through expression builders <strong>and</strong> data query<br />

parameter values.<br />

routeData Values<br />

The route parameters are available in code through the Page.RouteData.Values property, which is<br />

another instance of the RouteValueDictionary class. Similarly, data tokens are available through Page<br />

.RouteData.DataTokens. In the example web site, values are extracted from the Values property <strong>and</strong><br />

displayed through a DataGrid with the following code:<br />

if (Page.RouteData.Values.Count == 0)<br />

{<br />

this.NoRoutingLabel.Text = "None.";<br />

}<br />

else<br />

{<br />

GridView2.DataSource = from entry in Page.RouteData.Values<br />

select<br />

new<br />

{<br />

Name = entry.Key,<br />

Value = entry.Value<br />

};<br />

GridView2.DataBind();<br />

}<br />

code snippet PCSRoutingDemo/MasterPage.master.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!