views:

22

answers:

2

I have a rute in my asp.net mvc 2 site that looks like this

routes.MapRoute(
                "media_display",
                "Media/{mediaId}-{mediaName}",
                new { controller = "Media", action = "Display" },
                new { mediaId = @"\d+" }
            );

Where mediaId is the id, and mediaName is the title of the media. An example

www.example.com/Media/1-test-media-list

Where the id is 1, and the name is "test media list", the problem here is that i replace space " " with -, and that ruins my route.

I just can't figure out how to make this so "mediaName" can contain a -.

i also have the following rute, but the solution should be the same.

routes.MapRoute(
                "media_display",
                "Media/{mediaId}-{mediaName}/edit",
                new { controller = "Media", action = "Edit" },
                new { mediaId = @"\d+" }
            );

Also are it possible to make a route that will catch all the following 3 exampels, right now do i just have 3 different routes, but i would like to cut this down.

www.example.com/Media/1-test-media-list

www.example.com/Media/1-

www.example.com/Media/1

A: 

I have done this with a regex route i found at http://iridescence.no/post/Defining-Routes-using-Regular-Expressions-in-ASPNET-MVC.aspx

routes.Add(
    new RegexRoute(@"^Media\/(?<mediaId>\d+)-(?<mediaName>[^\/]*)$", 
        new MvcRouteHandler())
    {
        Defaults = new RouteValueDictionary(new { 
        controller = "Media", action = "Display", playlistName = "" })
    }
DoomStone
+1  A: 

I consider a more elegant and simpler solution to have www.example.com/Media/1/test-media-list.

If you insist on your url examples, make a route like this:

routes.MapRoute(
                "media_display",
                "Media/{slug}",
                new { controller = "Media", action = "Display" },
            );

and use technique described in this blog post to parse the id, name or whatever you need from the slug into you action parameters.

Necros
I would say that www.example.com/Media/1-test-media-list is the most elegant :DThe slug sulotion, will break the making of urls where i use Html.Action("Display", "Media", new { mediaId = 1, mediaName = "Some Name" } );But if no one are able to help me with the {mediaId}-{mediaName} sulotion will i use {mediaId}/{mediaName}
DoomStone
I used to have a property that returned generated slug in my view model when I used that. Then you would have Html.Action("Display", "Media", new { slug = Model.MediaSlug } ). But I still think /id/name is nicer. Look! Even SO uses it ;)
Necros
I have used the /id/name solution
DoomStone