asp.net Multiple Page_Load events for a user control when using URL Routing
- by Paul Hutson
Hello,
I've recently set up an ASP.net site (not using MVC.net) to use URL Routing (more on the code below) - when using user controls on the site (i.e I've created a "menu" user control to hold menu information) the page_load event for that control will fire twice when URLs have more than one variable passed over.
i.e.
pageName/VAR1 : will only fire the page_load event once.
while
pageName/VAR1/VAR2 : will fire the page_load event twice.
*Multiple extra VARs added on the end will still only fire the page_load event twice*.
Below are the code snippits from the files, the first is the MapPageRoute, located in the Global.asax :
// Register a route for the Example page, with the NodeID and also the Test123 variables allowed.
// This demonstrates how to have several items linked with the page routes.
routes.MapPageRoute(
"Multiple Data Example", // Route name
"Example/{NodeID}/{test123}/{variable}", // Route URL - note the NodeID bit
"~/Example.aspx", // Web page to handle route
true, // Check for physical access
new System.Web.Routing.RouteValueDictionary
{
{ "NodeID", "1" }, // Default Node ID
{ "test123", "1" }, // Default addtional variable value
{ "variable", "hello"} // Default test variable value
}
);
Next is the way I've directed to the page in the menu item, this is a list item within a UL tag :
<li class="TopMenu_ListItem"><a href="<%= Page.GetRouteUrl("Multiple Data Example", new System.Web.Routing.RouteValueDictionary { { "NodeID", "4855" }, { "test123", "2" } }) %>">Example 2</a></li>
And finally the control that gets hit multiple times on a page load :
// For use when the page loads.
protected void Page_Load(object sender, EventArgs e)
{
// Handle the routing variables.
// this handles the route data value for NodeID - if the page was reached using URL Routing.
if (Page.RouteData.Values["NodeID"] != null)
{
nodeID = Page.RouteData.Values["NodeID"] as string;
};
// this handles the route data value for Test123 - if the page was reached using URL Routing.
if (Page.RouteData.Values["Test123"] != null)
{
ExampleOutput2.Text = "I am the output of the third variable : " + Page.RouteData.Values["Test123"] as string;
};
// this handles the route data value for variable - if the page was reached using URL Routing.
if (Page.RouteData.Values["variable"] != null)
{
ExampleOutput3.Text = "I say " + Page.RouteData.Values["variable"] as string;
};
}
Note, that when I'm just hitting the page and it uses the default values for items, the reloads do not happen.
Any help or guidance that anyone can offer would be very much appreciated!
EDIT : The User Control is only added to the page once. I've tested the load sequence by putting a breakpoint in the page_load event - it only hits twice when the extra routes are added.
Thanks in Advance,
Paul Hutson