Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 and URLs (using areas, having an issue with building an <a> tag)

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.

like image 899
SlackerCoder Avatar asked Dec 13 '22 10:12

SlackerCoder


1 Answers

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...

like image 157
AJC Avatar answered May 15 '23 21:05

AJC