ASP.NET MVC Map String Url To A Route Value Object

Posted by mwgriffiths on Stack Overflow See other posts from Stack Overflow or by mwgriffiths
Published on 2010-06-14T11:03:01Z Indexed on 2010/06/14 11:42 UTC
Read the original article Hit count: 320

Filed under:
|
|
|
|

I am creating a modular ASP.NET MVC application using areas. In short, I have created a greedy route that captures all routes beginning with {application}/{*catchAll}.

Here is the action:

// get /application/index  
public ActionResult Index(string application, object catchAll)  
{  
  // forward to partial request to return partial view  
  ViewData["partialRequest"] = new PartialRequest(catchAll);  

  // this gets called in the view page and uses a partial request class to return a partial view  
}  

Example:

The Url "/Application/Accounts/LogOn" will then cause the Index action to pass "/Accounts/LogOn" into the PartialRequest, but as a string value.

// partial request constructor  
public PartialRequest(object routeValues)  
{  
  RouteValueDictionary = new RouteValueDictionary(routeValues);  
}  

In this case, the route value dictionary will not return any values for the routeData, whereas if I specify a route in the Index Action:

ViewData["partialRequest"] = new PartialRequest(new { controller = "accounts", action = "logon" });

It works, and the routeData values contains a "controller" key and an "action" key; whereas before, the keys are empty, and therefore the rest of the class wont work.

So my question is, how can I convert the "/Accounts/LogOn" in the catchAll to "new { controller = "accounts", action = "logon" }"??

If this is not clear, I will explain more! :)

Matt

This is the "closest" I have got, but it obviously wont work for complex routes:

// split values into array
var routeParts = catchAll.ToString().Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);  

// feels like a hack
catchAll = new
{
  controller = routeParts[0],
  action = routeParts[1]
}; 

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about string