How to specify an area name in an action link?

87,264

Solution 1

Figured it out..

Html.ActionLink("Link Text", "ActionName", "ControllerName", new { Area = "AreaName" }, new{})

Solution 2

Something I ran into right after this, that I imagine others might run into: If you need to link from within an area to an action not in an area, you still need to specify the Area as empty string.

For instance, I moved some MVC code into an area, and found I needed to update urls in the master page that referenced other pages on the site.

To specify an url to something not in an area, use

Html.ActionLink("home", "Index", new { area = "", controller = "Home" })

Solution 3

Use:

 Html.ActionLink("Text", "ActionName", "ControllerName", new { Area = "AreaName" }, null)

Note:4th parameter is to pass route Values, if you pass an empty parameter it will consider root structure and if you pass appropriate value it use it as area.

Also do not forget to use null or new{} as the 5th parameter because passing null or new {} while creating action link will not overload method for (text,action,controller,route data) or its (text,action,controller,route data,html attribute) so use the proper method

Solution 4

In MVC2 giving area="root" worked for me as below

Html.ActionLink("Home", "Index", "Home", new { Area = "root" }, new{})

Solution 5

A neat trick you can do if you are using an area a lot in a View is define it as a variable at the top:

@{ var awesomeArea = new { area = "Awesome" }; }

@Html.Action("Something", "Somewhere", awesomeArea)
@Html.ActionLink("Stuff", "FooBar", awesomeArea)
Share:
87,264

Related videos on Youtube

Jeremy
Author by

Jeremy

Software Developer

Updated on March 12, 2020

Comments

  • Jeremy
    Jeremy about 4 years

    I have a shared master page which I am using from 2 different areas in my mvc 2 app. The master page has an action link which currently specifies the controller and action, but of course the link doesn't work if I'm in the wrong area. I see no overload for actionlink that takes an area parameter, is it possible to do?

  • Alexander Beletsky
    Alexander Beletsky over 13 years
    This is a very good tip! But it gives not expected results with MVC 2.. Small correction - Html.ActionLink("home", "Index", new { area = "", controller = "Home" })
  • Jeremy
    Jeremy over 11 years
    @Pure.Krome - yes. Nothing intuitive about it!
  • Piotr Kula
    Piotr Kula almost 11 years
    Make sure there is not white space before or after the Areaname. Otherwise it will just ignore it... and then will make you wonder four hours what is wrong.. just like me.
  • Yorro
    Yorro almost 9 years
    How do you add parameters in there?
  • Travis J
    Travis J almost 8 years
    Explicitly setting the htmlAttributes: worked very well for using multiple parameters.
  • FrenkyB
    FrenkyB over 6 years
    How does this look like translated into link? I mean - when form is rendered and returned to the client.