Created
July 5, 2012 08:44
-
-
Save JefClaes/3052349 to your computer and use it in GitHub Desktop.
Extensions methods to create a top level menu based on areaname convention
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.Text; | |
using System.Reflection; | |
namespace TopMenuBasedOnAreas.HtmlHelpers | |
{ | |
public static class TopMenuExtensions | |
{ | |
private static IEnumerable<string> _areaNames; | |
public static MvcHtmlString RenderTopMenuItems(this HtmlHelper helper) | |
{ | |
var areaNames = GetAreaNames(); | |
var currentArea = helper.ViewContext.RouteData.DataTokens["area"] as string; | |
var html = new StringBuilder(); | |
foreach (var areaName in areaNames) | |
{ | |
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); | |
var url = urlHelper.Action(string.Empty, string.Empty, new { area = areaName }); | |
// var url = urlHelper.RouteUrl(areaName + "_default"); | |
html.AppendLine(areaName.Equals(currentArea, StringComparison.OrdinalIgnoreCase) ? "<li class='active'>" : "<li>"); | |
html.AppendLine(string.Format("<a href='{0}'>{1}</a>", url, areaName)); | |
html.AppendLine("</li>"); | |
} | |
return new MvcHtmlString(html.ToString()); | |
} | |
private static IEnumerable<string> GetAreaNames() | |
{ | |
if (_areaNames == null) | |
{ | |
_areaNames = Assembly | |
.GetExecutingAssembly() | |
.GetTypes() | |
.Where(t => t.IsClass && typeof(AreaRegistration).IsAssignableFrom(t)) | |
.Select(a => (AreaRegistration)Activator.CreateInstance(a)) | |
.Select(r => r.AreaName); | |
} | |
return _areaNames; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment