[RESOLVED]Realtion between Routes & HTML.Actionlinks when generating outgoing urls

I have defined the following action link inside my Index view under Home controller:-

    @Html.ActionLink("Create New", "Create")

And I added the followingNewRoute:-

 public static void RegisterRoutes(RouteCollection routes)
            routes.MapRoute("NewRoute", "App/Do{action}",
new { controller = "Home" });
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Now if i add the @Html.ActionLink("Create New", "Create") inside the Home controller’s index view the generated urls will be:-


So I can not understand how did the action method generate its URL ? seems that it used the custom route to generate the URL, and the strange thing is that if I define the above action method inside let say Customer controller’s index view, then the generate
URL will be correct such as :-


so what si the relation between Routes and Actionlinks?


ActionLinks generate links from the routes you have defined, as do RouteLinks. The difference between them is the information you provide to them. ActionLinks require an action name (and optionally a controller name), and will then generate a url based on
your routes to reach that action. RouteLinks take a route name, not an action, and will generate a URL based on the route.


@Html.ActionLink("Create New", "Create")

In your scenario, you are not passing the Controller name to the ActionLink, you are just passing the Action name. MVC substitutes current controller as the controller name. If you have you code in Home controller, then you are looking at  Home/Create. If
you have the same code at CustomerController, then your link will be Customer/Create

With your custom routing, you defined a specific url for HomeController. Hence in your first scenario (with HomeController) it uses that route. In your second scenario MVC uses the default route.

Leave a Reply