2

I am trying here to kinda merge 2 routes in 1 with asp.net mvc

These routes are :

http://www.example.com/e/1

and

http://www.example.com/e/1,name-of-the-stuff

Currently it is set as this in the Global.asax.cs :

routes.MapRoute(
    "EventWithName",
    "e/{id},{name}",
    new { controller = "Event", action = "SingleEvent", id = "" },
    new { id = @"([\d]+)" }
);

routes.MapRoute(
    "SingleEvent",
    "e/{id}",
    new { controller = "Event", action = "SingleEvent", id = "" },
    new { id = @"([\d]+)" }
);

I tried to handle it by modifying the 1st route like this one :

routes.MapRoute(
    "EventWithName",
    "e/{id}{name}",
    new { controller = "Event", action = "SingleEvent", id = "" },
    new { id = @"([\d]+)", name = @"^,(.*)" }
);

It is not working as I need to separate the 2 parameters with a slash or at least a character.

My most possible idea to solve this would be using the regex, as I only need the id part. The name is only descriptive and used for SEO purposes. Basically is there a way to use some kind of Regex of the type of ([\d]+),(.*) and the for id = "$1" or something like that ?

1 Answer 1

3

Maybe it helps

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}/{*keywords}",
    new { controller = "Home", action = "Index", id = 0 },
    new { id = "(\\d+)" }
);
Sign up to request clarification or add additional context in comments.

4 Comments

I would need to format my URLs like this : example.com/Events/SingleEvent/1/name-of-the-stuff, which is not exactly what I look for.
Not necessarily. The key point of this answer is the {keywords} part. Try adding the '' to your route, with the comma. If the ",foo" part is optional, try using two routes, first with both parts, second with just the {id}.
Brannon is right. I think the format /1/what-is-new is better than /1,what-is-new. As you can see in the StackOverflow qustion url. anyway, you can not use two parameters in the same segment or a literal text between them.
It seems it is the easiest way to work around. I'll use it for now and see later I guess :-) thanks for the pointer!

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.