I have a page route with an optional “id” parameter. Defined like so:
routes.MapPageRoute(null,
"projects/{operation}/{id}",
"~/Projects/ProjectWizard.aspx",
true,
new RouteValueDictionary(new
{
operation = "new",
id = UrlParameter.Optional
}),
new RouteValueDictionary(new
{
operation = @"new|edit",
id = @"\d*"
})
);
The route works fine, but when I get to the page if I haven’t included the optional “id” parameter then my code fails when trying to convert to integer.
var operation = RouteData.Values["operation"].ToString();
var projectId = RouteData.Values.ContainsKey("id") ? Convert.ToInt32(RouteData.Values["id"]) : 0;
This works great as long as I pass in an ID in the route like this:
http://webapp/projects/edit/123
projectId is equal to 123 just like it should be. But if I don’t include the ID:
http://webapp/projects/new
The route goes to the page fine but I get this error:
Unable to cast object of type ‘System.Web.Mvc.UrlParameter’ to type ‘System.IConvertible’.

It should be unable to find the key in the route data values and then assign a zero to projectId, but it doesn’t. I keep trying different ways to check for null for the “id” route value but it doesn’t seem to like that very much.
That would work perfectly were you dealing with MVC controller actions here and MapRoute.
What I would do in your case is simply set the default for your id in the defaults instead of UrlParameter.Optional, so:
then simply read your id like so: