I need an implementation where I can get infinite parameters on my ASP.NET Controller. It will be better if I give you an example :
Let's assume that I will have following urls :
example.com/tag/poo/bar/poobar example.com/tag/poo/bar/poobar/poo2/poo4 example.com/tag/poo/bar/poobar/poo89
As you can see, it will get infinite number of tags after example.com/tag/
and slash will be a delimiter here.
On the controller I would like to do this :
foreach(string item in paramaters) { //this is one of the url paramaters string poo = item; }
Is there any known way to achieve this? How can I get reach the values from controller? With Dictionary<string, string>
or List<string>
?
NOTE :
The question is not well explained IMO but I tried my best to fit it. in. Feel free to tweak it
there are no limits in creating routes. You can create as many route as you want in your RouteConfig.
Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.
In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.
Like this:
routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... }); ActionResult MyAction(string tags) { foreach(string tag in tags.Split("/")) { ... } }
The catch all will give you the raw string. If you want a more elegant way to handle the data, you could always use a custom route handler.
public class AllPathRouteHandler : MvcRouteHandler { private readonly string key; public AllPathRouteHandler(string key) { this.key = key; } protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { var allPaths = requestContext.RouteData.Values[key] as string; if (!string.IsNullOrEmpty(allPaths)) { requestContext.RouteData.Values[key] = allPaths.Split('/'); } return base.GetHttpHandler(requestContext); } }
Register the route handler.
routes.Add(new Route("tag/{*tags}", new RouteValueDictionary( new { controller = "Tag", action = "Index", }), new AllPathRouteHandler("tags")));
Get the tags as a array in the controller.
public ActionResult Index(string[] tags) { // do something with tags return View(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With