Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC with Areas -- Html.ActionLink returning wrong URL/Route?

I am using MVC3 and have Areas in my application. In general, everything works fine, I can navigate to my area (e.g. Admin=Area, Controller=Department) like this:

<%: Html.ActionLink("Departments", "DepartmentIndex", "Department", new { area = "Admin"}, null )%>

However, what I noticed is that if I don't specify the area in my ActionLink, e.g.

<%: Html.ActionLink("Test", "Index", "Home")%>

This will stop working if I have navigated to the "Admin" area. i.e. my url is now http://localhost/myproj/Admin/Home/Index instead of http://localhost/myproj/Home/Index

Any ideas on what is going on here?

My routes are all the defaults when creating an MVC app / Areas. i.e.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
            new[] { "MyProj.Controllers" } 
        );
    }

And my area registration

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

Is this by design? This posting suggests using RouteLink instead of ActionLink: say to use RouteLink Is it required to have "area" routevalue on actionlink if the application was grouped into areas?

like image 747
Raymond Avatar asked May 25 '11 23:05

Raymond


People also ask

What is the difference between using URL action and HTML ActionLink in a view?

There is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do I transfer my ActionLink model to my controller?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to send Model data (object). Hence in order to pass (send) Model data (object) from View to Controller using @Html.


1 Answers

This StackOverflow answer correctly states that you need to provide the Area name if you're using areas.

eg.

Html.ActionLink("Home", "Index", "Home", new { Area = "" }, new { })
like image 117
Pure.Krome Avatar answered Oct 31 '22 13:10

Pure.Krome