ASP.MVC paths without detailed actions

I would like to have URLs that are even shorter than / {Controller} / {Action} / {Id}.

For example, I would like {Controller} / {Id}, where {Id} is a string.

This will allow you to use simple paths, for example. Users / Username, Pages / Pagename, News / Newsname. I like it better than the requirement / Detailed action in the URL (Users / Details / Username), which is less elegant for the end user.

I can easily do this job by setting up custom routes for any controller for which I want this level of simplicity. However, this causes headaches when implementing other actions, such as {Controller} / {Action}, where {Action} = 'Create', because in this case the line {Action} conflicts with the line {Id}.

My question is: how can I "reserve" the words, so if the URL is / News / Create, it is considered as an action, but if the URL is something else, for example. / News / A-gorilla-ate-my -thesis, then it is considered as Id.

I hope I can determine this when setting up routes?

Update:

Using Ben Griswold's answer, I updated the ASP.NET default MVC routes:

routes.MapRoute( "CreateRoute", // route name "{controller}/Create", // url with parameters new { action = "Create" } // parameter defaults ); routes.MapRoute( "DetailsRoute", // route name "{controller}/{id}", // url with parameters new { action = "Details" } // parameter defaults ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); 

This works like a charm and means that by default the pages with detailed information will use a simplified URL, but I can still target a specific action if I want to (update / delete / details).

Of course, you will need to prohibit the reserved word "Create" as an identifier, otherwise the user may try to create an article, for example, with the name "Create", which can never be accessed.

This is really nice. If someone sees that something is wrong with this approach, turn on the sound, but I still like it.

+7
asp.net-mvc-routing asp.net-mvc-2
source share
1 answer

I think that you have to create a route for each reserved word. For example,

 routes.MapRoute("CreateRoute", "{controller}/Create", new { action = "Create" } ); 

will handle / News / Create, / Users / Create, etc. As long as this route is pointed to your other custom route, I think you are covered.

I assume that you will need additional routes for various CRUD operations that will follow a similar pattern.

+4
source share

All Articles