问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/34467408/what-is-the-purpose-of-area-in-an-html-actionlink