I am converting routes from a Rails Application to work with a replacement Asp.net MVC application. We need to maintain all the old urls. Most of the routes convert over without issues - but I am having a bit of difficulty figuring out what to do with this one...
The actual url is all hyphenated like this
site.com/agent-name-ratings-city-name-123
The Rails Route is defined as
get '/:agent_name-ratings-:city-:id' => 'agents#show'
I only need to pass the "agent-name" as the {id} to the Asp {agents} controller. My problem is what to do with the city-name and id that come in at 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 -- it seems to mess up the @Html.ActionLink...
@Html.ActionLink("View", "Profiles", "Agents", new { id = item.first_name + "-" + item.last_name }, null)
It ends up pointing to...
site.com/Agents/Profiles/agent-name
which is a valid url, just not the one we want.
SO - How do I get this link in the format that's needed?
site.com/agent-name-ratings-city-123
The city-name and id are both available from the "item" object. The word "ratings" is a constant. I'm just not sure how to blend it all together.
Any suggestions would be appreciated, thanks!
答案 0 :(得分:1)
The main issue is you have Url params specified in the route, however they don't appear in your Html.ActionLink
definition, so the default route gets used as there is no definitive 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)
Otherwise, add UrlParameter.Optional
to the 2 additional fields in the map route.
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 making the params optional will cause malformed URL's if you only specify the id
portion in the action link.
e.g. site.com/agent-name-ratings--
Edit
Also making the Url params optional will most likely break your other routes that are specifying id
in the params. However this would probably work, and not break too many things, but will still have malformed URL's:
@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 });