Reputation: 1351
Im having an issue with areas and generating links from them. Here's the rough structure of the code Im working with:
Home
Area1
Area 1 Content
Area2
Area 2 Content
Area3
Area 3 Content
In my _layout.cshtml file I generate a menu (which is completely table driven):
foreach (MainMenu mm in parentMenus)
{
List<SubMenu> theseChildren = childMenus.Where(o => o.MainMenuId == mm.MainMenuId).OrderBy(p => p.Ordering).ToList();
result.Append(String.Format(@"<h3><a href='#'>{0}</a></h3>", mm.Name));
result.Append(String.Format(@"<div>"));
result.Append(String.Format(@"<p>"));
foreach(SubMenu sm in theseChildren){
//Issue is here:
result.Append(String.Format(@"<a href='{0}/{1}/{2}'>{3}</a> <br />", sm.AreaName == null ? String.Empty : sm.AreaName, sm.ControllerName, sm.ActionName, sm.Name));
}
result.Append(String.Format(@"</p>"));
result.Append(String.Format(@"</div>"));
}
It's built this was since it's being generated for an accordion (jQuery).
So, the issue is in the foreach loop. When the code is running in the "Home" area it's fine, but when it's running outside of the home area, it generates odd results.
So, for example, I have a record in the database call OPS. It should create a link to OPS/OPS/INDEX (area = OPS, Controller = OPS, Action = INDEX). In the home "area", it's fine, but when it's in an area, it comes out "http://localhost:17416/Home/OPS/OPS/INDEX"
Any help that can provided would be great!
Thanks in advance everyone.
Upvotes: 4
Views: 6135
Reputation: 296
This above marked answer will not work the area should be in A capital
@Url.Action("Action", "Controller", new { Area = "AreaName" }, null)
@Html.ActionLink("Label", "Action", "Controller", new { Area = "AreaName" }, null)
Upvotes: 0
Reputation: 27585
use this:
String.Format(
"<a href='{0}'>some text you want</a>",
Url.Action("ActionName", "ControllerName", new { area = "AreaName" })
);
instead of:
String.Format(
@"<a href='{0}/{1}/{2}'>{3}</a> <br />",
sm.AreaName == null ? String.Empty : sm.AreaName,
sm.ControllerName,
sm.ActionName, sm.Name)
for example:
String.Format(
"<a href='{0}'>{1}</a>",
Url.Action(sm.ActionName, sm.ControllerName, new { area = sm.AreaName }),
sm.Name
);
Upvotes: 6
Reputation: 1893
You have to change your code to specify an Area in the link like so:
@Html.ActionLink("Label", "Action", "Controller", new { area = "Area" }, null)
This should work:
foreach(SubMenu sm in theseChildren){
result.Append(@Html.ActionLink(sm.Name, sm.ActionName, sm.ControllerName, new { area = sm.AreaName }, null).ToHtmlString());
}
Hope this helps...
Upvotes: 7