Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2 Parameter Array

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.

like image 629
Sonia Avatar asked Sep 03 '10 09:09

Sonia


People also ask

What is difference between FromQuery and FromBody?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.


2 Answers

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() }) %>
like image 195
Jeroen Avatar answered Oct 24 '22 18:10

Jeroen


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

like image 45
Cioxideru Avatar answered Oct 24 '22 17:10

Cioxideru