Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC ActionLink generating different types of links... why?

I'm new to MVC land, and have an app that i'm working on. i have 2 different links with 2 routes in my global which are fairly similiar

route 1

routes.MapRoute("Category", "Movies/{category}/{subcategory}", 
    new { controller = "Catalog", action = "Index", category = "", subcategory = "" });

route 2

routes.MapRoute("Movie", "Movie/{movie}", 
    new { controller = "Movie", action = "Index", movie = "" });

When i call an actionlink for the first route it creates it as i would think it should:

.../Movies/Category/SubCategory

however when i create my second link it populates it like this:

.../Movie?movieId=ff569575-08ec-4049-93e2-901e7b0cb96a

I was using a string instead of a guid before and it was still doing the same i.e.

.../Movie?movieName=Snatch

my actionlinks are set up as follows

<%= Html.ActionLink(parent.Name, "Index", "Catalog",
    new { category = parent.Name, subCategory = "" }, null)%>

<%= Html.ActionLink(movie.Name, "Index", "Movie", 
    new { movieId = movie.MovieId }, null)%>

My app still works, but i thought this behavior was strange. any help would be great.

Thanks!

like image 907
Dacrocky Avatar asked Jan 24 '23 19:01

Dacrocky


2 Answers

routes.MapRoute("Movie", "Movie/{movieId}", 
    new { controller = "Movie", action = "Index", movie = "" });

Should the route text not match the name of the property which you are submitting to the mvc link?

like image 187
REA_ANDREW Avatar answered Jan 26 '23 10:01

REA_ANDREW


The problem is that when you call ActionLink, the routing system can't figure out which of the two routes to use, so it chooses the first. The solution is to use RouteLink instead of ActionLink. RouteLink lets you specify the name of the route to use when generating the URI. Then there is no ambiguity as to which route to use. I think that ActionLink is obsolete. I can think of no reason to use it in lieu of of RouteLink.

However, you may still have a problem when the user submits links. In that case, use route constraints to enforce the selection of the correct route.

Andrew is correct (up-voted) that the tokens you use in ActionLink/RouteLink and the route itself must match.

like image 43
Craig Stuntz Avatar answered Jan 26 '23 09:01

Craig Stuntz