2

When I use Visual Studio 2013 to create a new MVC project, I notice that in the _Layout.cshtml file, there is a default link in the menu bar.

@Html.ActionLink("Application name", "Index", "Home", 
      new { area = "" }, new { @class = "navbar-brand" })

It all makes sense for me except the new { area = ""} part. Intellisense says that this parameter is for route values.

I did a Google search for "Html.Actionlink route value area" (and other permutations), but was unable to find any simple definitions of what an "area" is.

Is there a simple explanation for what an "area" is? I have never used this attribute in any of my ActionLinks before.

2 Answers2

4

This tells to create an action link to Home/Index on the root of the app. You will usually use this when you want to use the Html.ActionLink() method to create a link from a view under an area.

If you do not specify the area value as an empty string, It will create a link pointing to YourCurrentAreaName/Home/Index

Areas are logical grouping of your functionality. You can think it like sub modules of your application ( Ex: Blog / Admin etc). Here is a video tutorial about areas which should help you to understand it.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I see how the second and third parameters (action and controller names) do that. But what does the "area" have to do with it? Or more to the point, what is an "area"? –  Dec 25 '15 at 23:54
  • Areas are logical grouping of your code. http://www.asp.net/mvc/videos/mvc-2/how-do-i/aspnet-mvc-2-areas – Shyju Dec 25 '15 at 23:57
  • The link you just mentioned is what makes the explanation complete. I learned something completely new (and useful). You should add that to the answer. –  Dec 26 '15 at 00:02
0

This behavior is not limited to just Areas, in fact this is a confusing part of MVC behavior that they insist is by design. As per the advice from Microsoft, you must provide route values explicitly if you want to override the values that are injected automatically from the current request.

Therefore, if you are looking at a view from the default area, the URL generated from this action link will point to the default area.

@Html.ActionLink("Application name", "Index", "Home", 
  null, new { @class = "navbar-brand" })

/Home/Index

However, if you happen to be viewing the result of an action that is from the Admin area, the URL from that action link will also be in the Admin area.

/Admin/Home/Index

So, in order to override the default behavior, you need to explicitly specify that the area is the default by using an empty string.

@Html.ActionLink("Application name", "Index", "Home", 
  new { area = "" }, new { @class = "navbar-brand" })

This ensures that whatever area the current view is, the URL will be for the default area.

/Home/Index

NightOwl888
  • 55,572
  • 24
  • 139
  • 212