Set default area - Avoiding `, new {area = ""}` on each link on the site
Asked Answered
U

2

9

This code is inside the master page:

<li><a href="<%=Url.Action("Action", "Controller") %>">Main site link</a></li>
<li><a href="<%=Url.Action("AreaAction", "AreaController", new {area = "Area"}) %>">Area link</a></li>

All the links works good till I'm going to the Area Link. When I go there all the routes of the main area don't work.

To fix that I can use this:

<li><a href="<%=Url.Action("Action", "Controller", new {area = ""}) %>">Main site link</a></li>

My question is, is there a way to avoid , new {area = ""} on every link in the to the main site?

Its very annoying to have this on every link on the site.

Unasked answered 16/2, 2010 at 5:29 Comment(0)
P
11

Url actions are relative to the location of the link. So new {area = ""} is not telling the Url.Action call that there is no area, it's telling it to use the root area. If you omit new {area = ""} from the Url.Action call it will try to create a url for the specified action within the specified controller within the current area (the "Area" are in your case).

Therefore it is unavoidable if you want to link from a subarea to the root area.

Proclus answered 16/2, 2010 at 18:19 Comment(1)
Which answers the specific question I was googling: Why do links created Url.Action magically resolve to references within the current area. Thank you!Joby
V
4

I still don't know of away around it if you are using the standard MVC methods (other than maybe overriding them to call your own version), but if you are using the ActionLink<TController> or other generic methods provided in the MvcFutures lib then you can.

The MvcFutures methods call ExpressionHelper.GetRouteValuesFromExpression(), which looks for an ActionLinkAreaAttribute on the controller to determine the area. So you can decorate your controllers in your main "area" as follows:

[ActionLinkArea("")]
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

The action links should be generated correctly using the standard syntax:

<%= Html.ActionLink<HomeController>(c => c.Index(), "Home") %>
Vento answered 8/3, 2010 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.