Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Last active December 26, 2015 12:09
Show Gist options
  • Save danielmackay/7149309 to your computer and use it in GitHub Desktop.
Save danielmackay/7149309 to your computer and use it in GitHub Desktop.
MVC Helpers for generating links or sections with toggleable css classes (e.g. for highlighting). #mvc
public class ListItemSection : DivSection
{
public ListItemSection(HtmlHelper self, string className = null)
: base(self, className, "li")
{
}
}
public class DivSection : IDisposable
{
protected HtmlHelper helper;
protected string element;
public DivSection()
{
}
public DivSection(HtmlHelper helper, string className = null, string element = "div")
{
this.helper = helper;
this.element = element;
helper.ViewContext.Writer.Write(GetStart(className));
}
public void Dispose()
{
helper.ViewContext.Writer.Write(GetEnd());
}
private string GetStart(string className)
{
var sb = new StringBuilder();
sb.AppendFormat("<{0} ", element);
if (!string.IsNullOrWhiteSpace(className))
sb.AppendFormat("class=\"{0}\"", className);
sb.Append(" />");
return sb.ToString();
}
private string GetEnd()
{
return string.Format("</{0}>", element);
}
}
public static class MvcHelpers
{
public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string action, string controller, string cssClass = "currentMenuItem")
{
if (IsActionMatch(helper, action, controller))
return helper.ActionLink(text, action, controller, null, new { @class = cssClass });
return helper.ActionLink(text, action, controller);
}
public static ListItemSection ActiveListItemSection(this HtmlHelper self, string action, string controller, string className)
{
if (IsActionMatch(self, action, controller))
return new ListItemSection(self, className);
return new ListItemSection(self);
}
private static bool IsActionMatch(HtmlHelper helper, string action, string controller)
{
var routeData = helper.ViewContext.RouteData.Values;
var currentController = routeData["controller"] as string;
var currentAction = routeData["action"] as string;
bool actionMatch = action.Equals(currentAction, StringComparison.OrdinalIgnoreCase) &&
controller.Equals(currentController, StringComparison.OrdinalIgnoreCase);
return actionMatch;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment