views:

244

answers:

1

Is there any way to get truly restful routing working in MVC, just like the rails dudes have? I 'm talking about nested urls like /bands/metallica/albums/killemall/track/4

The only library that I found to be useful is Steve Hodgkiss' Restful routing. It seems though a bit risky to base my whole project's routing on this guy's pet-project.

What say you MVC veterans?

+4  A: 

Sure:

routes.MapRoute("IwannaBeLikeTheCoolRailsKids",
                "bands/{bandName}/albums/{albumName}/tracks/{trackNumber}",
                new { controller = "Bands",
                action = "ByTrack" 
               });

Then in your controller:

public ActionResult ByTrack(string bandName, string albumName, int trackNumber)

Easy peasie.

Wyatt Barnett
Man, you wrote alb**l**um all over the place! :)
Martinho Fernandes
Nice touch with IWannaBeLikeTheCoolRailsKids...
Martinho Fernandes
How would you handle this url? /bands/metallica/albums/killemall/track/the-four-horsemen
mxmissile
without losing the int track url functionality
mxmissile
Spelling wasn't my strong suit. As for the second part, there isn't a way to remove the track number from the URL and still use it as a parameter. Rather, what you'd need to do is make it so you could find the song by a url slug field.
Wyatt Barnett
Like this? /bands/metallica/albums/killemall/track/4/the-four-horsemenWhat would the method signature look like for that?
mxmissile
Maybe you want to ask your own question . . .
Wyatt Barnett
So you think that there's no merit in the approach implemented by Steve Hodgkiss? Any kind of RESTful route can be handled by adding more specific routes to the default MVC routing engine?
thanos panousis
Nah, I think it is a great approach in some cases, was really answering the question about how to do custom routing in general in .NET MVC.
Wyatt Barnett
The problem with this approach is what do you do when the entities themselves are not hierarchical. Meaning that the track number is really a unique key for a song in the database.what do you do if the user changes the url to a different album name and what not, but keeps the last ID of the song the same? do you serve the song-detail page, or do you show a 404?And how do you handle that in your controllers in a general fashion?
thanos panousis
My thought is anyone who manually changes the url to try and find a result deserves a 404 if the there is nothing there. Why write several hours of extra code to accommodate someone who is too lazy to go through your UI to find what they are looking for. I agree, url's need to be user friendly, but don't break your back thinking and coding routes for someone who is tinkering with your urls outside of the UI.
DM