9

I need to have the following routing logic:

http://mydomain.com/myAction/{root}/{child1}/{child2}/...

I don't know what is the depth of the route so I want the action's signature to look something like that:

public ActionResult myAction(string[] hierarchy)
{
  ...
} 

Have no idea how to write that route. Help?

Thanks a lot.

2 Answers 2

15

When you add the following mapping:

routes.MapRoute("hierarchy", "{action}/{*url}"
    new { controller = "Home", action = "Index" });

you can obtain the string 'url' in your action method:

public ActionResult myAction(string url)
{
    ...
}

The hierarchy is then easily obtained:

string[] hierarchy = url.Split('/');

Creating an url from a list of string values can be done using a similair approach:

string firstPart = hierarchy.Count() > 0: hierarchy[0] : string.Empty;
StringBuilder urlBuilder = new StringBuilder(firstPart);
for (int index = 1; index < hierarchy.Count(); index++)
{
    urlBuilder.Append("/");
    urlBuilder.Append(hierarchy[index]);
}

urlBuilder can then be used in an action link, for example:

<%= Html.ActionLink("Text", new { Controller="Home", Action="Index", Url=urlBuilder.ToString() }) %>
Sign up to request clarification or add additional context in comments.

3 Comments

I haven't checked that yet but it seems to work. What about rendering a route link? I would like to pass an array as route data. Any Ideas?
I've added an approach to the post.
Works perfectly! It is a matter of style but instead of using writing urlBuilder, I used string.Join("/", strArray). Thank you
1

for this problem your need to use strongly typed urlBuilder. Like T4MVC

1 Comment

Why would that help? Can you give an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.