Wednesday, November 3, 2010

Getting the Action or DynamicDataRoute from a DynamicData page

If you are working in a Dynamic Data web application sometimes you may need to know what the Action (List, Details, Edit, Insert) is. The Action is just a string and is set in the Global.asax.cs in the RegisterRoutes() method that is called on application startup. Actually, if you look at each route that is added, the object being added is a DynamicDataRoute object. This is the object we eventually want to access since it has our Action property.

When you are on a PageTemplate, a CustomPage, EntityTemplate, or a UserControl that you use in one of the previous items you have access to a class called DynamicDataRouteHandler. It has a static method called GetRequestContext() which has a RouteData property. This gives us the RouteData object which has a Route property which is of type BaseRoute. Remember, we need to get an instance of the DynamicDataRoute. As it turns out DynamicDataRoute is a subclass of Route which is a subclass of BaseRoute. So, all we have to do is cast the BaseRoute object we now have to a DynamicDataRoute and we now have access to the Action property.

I guess that is a lot of explaining for a few lines of code :) Here is the code.

RouteData route = DynamicDataRouteHandler.GetRequestContext(Context).RouteData;
DynamicDataRoute ddRouteData = route.Route as DynamicDataRoute;
string action = ddRouteData.Action;

No comments: