Translating Rails route to MVC Asp.net route

I am converting routes from a Rails app to work with an Asp.net replacement MVC app. We need to maintain all the old urls. Most routes convert without issue - but I'm having a hard time figuring out what to do with it ...

The actual url is all wrapped this way

site.com/agent-name-ratings-city-name-123

      

The Rails route is defined as

get '/:agent_name-ratings-:city-:id' => 'agents#show'

      

I need to pass "agent-name" as {id} to the Asp controller {agents}. My problem is what to do with the city name and id that go into the end of the url ...?

I've tried the following:

routes.MapRoute(name: "agents", url: "{id}-ratings-{city}-{agent_id}", defaults: new { controller = "Agents", action = "Profiles", id = "{id}" });

      

This works BUT - seems to have messed up @ Html.ActionLink ...

@Html.ActionLink("View",  "Profiles", "Agents",  new { id = item.first_name + "-" + item.last_name }, null)

      

It ends by pointing to ...

site.com/Agents/Profiles/agent-name

      

which is a valid url, not the one we want.

SO - How do I get this link in the format I want?

site.com/agent-name-ratings-city-123

      

The city name and identifier are available from the "item" object. The word "ratings" is a constant. I just don't know how to mix it all up.

Any suggestions would be appreciated, thanks!

+3


source to share


1 answer


The main problem is that you have the Url parameters specified on the route, however they don't appear in the definition Html.ActionLink

, so the default route is used as there is no final match.

Try the following:

@Html.ActionLink("View",  "Profiles", "Agents",  new { id = item.first_name + "-" + item.last_name, city = item.city, agent_id = item.agent_id }, null)

      

If not, add a UrlParameter.Optional

map to the two additional route fields.

routes.MapRoute(
            name: "agents", 
            url: "{id}-ratings-{city}-{agent_id}", 
            defaults: new { controller = "Agents", action = "Profiles", id = "{id}", city = UrlParameter.Optional, agent_id = UrlParameter.Optional });

      



However, if the parameters are optional, it will result in an incorrect URL if you only provide a part id

in the action link. egsite.com/agent-name-ratings--

Edit

Also, optional Url parameters are likely to break your other routes that you specify id

in parameters. However, this will probably work, rather than break too many things, but will still have invalid urls:

@Html.ActionLink("View", "Profiles", "Agents", new { agent_name = "agent" + "-" + "name" }, null)

routes.MapRoute(
            name: "agents", 
            url: "{agent_name}-ratings-{city}-{agent_id}",
            defaults: new { controller = "Agents", action = "Profiles", agent_name = "{agent_name}", city = UrlParameter.Optional, agent_id = UrlParameter.Optional });

      

+1


source







All Articles