Search code examples
c#asp.net-mvc-5razor-2

Appropriate use of Html.ActionLink for a specific rule


I have this rule in the RouteConfig:

routes.MapRoute(
    name: "UserProfile",
    url: "users/{uid}",
    defaults: new { controller = "Users", action = "Profile" }
);

How do I link to this action using @Html.ActionLink? It is easy enough to do it using @Html.Routelink but is it possible to do using the former?


Solution

  • You simply need to pass in the action name, controller name, and then an object that contains other route values, which in this case is uid

    @Html.ActionLink("User Profile", "Profile", "Users", new { uid = 1 }, null)
    

    If this doesn't translate into /users/{uid} because of how your routes are setup, then you should use @Html.RouteLink(). @Html.ActionLink() is for linking to an action directly. You provide the action and controller, and it gives a url based off of the routes that you have set up. If there are conflicting routes, you may not get the url you are expecting. In this case, linking to the route you want is the way to go.