Erick
Erick

Reputation: 6089

asp.net mvc optional parameter

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 ?

Upvotes: 2

Views: 1181

Answers (1)

m3kh
m3kh

Reputation: 7941

Maybe it helps

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}/{*keywords}",
    new { controller = "Home", action = "Index", id = 0 },
    new { id = "(\\d+)" }
);

Upvotes: 3

Related Questions