재우니의 블로그

ASP.NET MVC 의 ROUTING 으로 AREA, ACTION, VIEW 를 URL 찾아서 VIEW 화면에서 다양하게 사용할 수 있는 HELPER

 

사용법 : iselected : @Html.IsSelected(area:"Account", controller:"Admin", action: "Index")

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace Univ.Base.Web
{
    public static class MenuHelpers
    {
        /// <summary>
        /// Determines whether the specified area is selected.
        /// </summary>
        /// <param name="html">The HTML.</param>
        /// <param name="area">The area.</param>
        /// <param name="controller">The controller.</param>
        /// <param name="action">The action.</param>
        /// <param name="cssClass">The CSS class.</param>
        /// <returns></returns>
        public static string IsSelected(this HtmlHelper html, string area = null, string controller = null, string action = null, string cssClass = null)
        {

            if (String.IsNullOrEmpty(cssClass)) 
                cssClass = "active";

            string currentAction = (string)html.ViewContext.RouteData.Values["action"];
            string currentController = (string)html.ViewContext.RouteData.Values["controller"];
            string currentAreaName = (string)html.ViewContext.RouteData.DataTokens["area"];

            if (String.IsNullOrEmpty(controller))
                controller = currentController;

            if (String.IsNullOrEmpty(action))
                action = currentAction;

            if (String.IsNullOrEmpty(area))
                area = currentAreaName;

            return area == currentAreaName && controller == currentController && action == currentAction ?
                cssClass : String.Empty;
        }

        public static string PageClass(this HtmlHelper html)
        {
            string currentAction = (string)html.ViewContext.RouteData.Values["action"];
            return currentAction;
        }

    }
}