MVC3 and URLs (using areas having trouble creating the <a> tag)
I have a problem with areas and creating links from them. Here's the rough structure of Im code working with:
home
Area1
Area 1 Content
Area2
Area 2 Content
Space3
Area 3 Contents
In my _layout.cshtml file, I create a menu (which is fully 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>")); } He built it because it is created for an accordion (jQuery).
So the problem is in the foreach loop. When the code works in the Home area, this is normal, but when it works outside the home area, it generates odd results.
So, for example, I have an entry in the OPS database. It should create a link to OPS / OPS / INDEX (scope = OPS, Controller = OPS, Action = INDEX). In the home "area", this is normal, but when it is in the area, it goes out "http: // localhost: 17416 / Home / OPS / OPS / INDEX"
Any help that could be provided would be great!
Thanks in advance to everyone.
use this:
String.Format( "<a href='{0}'>some text you want</a>", Url.Action("ActionName", "ControllerName", new { area = "AreaName" }) ); instead:
String.Format( @"<a href='{0}/{1}/{2}'>{3}</a> <br />", sm.AreaName == null ? String.Empty : sm.AreaName, sm.ControllerName, sm.ActionName, sm.Name) eg:
String.Format( "<a href='{0}'>{1}</a>", Url.Action(sm.ActionName, sm.ControllerName, new { area = sm.AreaName }), sm.Name ); You need to change your code to indicate the area in the link like this:
@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 ...