Select the Controller name using JavaScript

1

I have the following code and would like to add class="current" to <li></li> according to the controller I'm accessing.

I want to do this to make the item stand out.

  <ul class="nav">
   <!-- Main menu -->
   <li class="current"><a href="index.html"><i class="glyphicon glyphicon-home"></i> Dashboard</a></li>
   <li><a href="calendar.html"><i class="glyphicon glyphicon-calendar"></i> Calendar</a></li>
   <li><a href="stats.html"><i class="glyphicon glyphicon-stats"></i> Statistics (Charts)</a></li>
   <li><a href="tables.html"><i class="glyphicon glyphicon-list"></i> Tables</a></li>
   <li><a href="forms.html"><i class="glyphicon glyphicon-tasks"></i> Forms</a></li>
   <li class="submenu">
      <a href="#">
      <i class="glyphicon glyphicon-list"></i> Pages
      <span class="caret pull-right"></span>
      </a>
      <!-- Sub menu -->
      <ul>
         <li><a href="login.html">Login</a></li>
         <li><a href="signup.html">Signup</a></li>
      </ul>
   </li>
</ul>

How do I get the name of the controller / action in the view?

I thought of getting the controller / action name and jQuery to change the <li></li> class.

    
asked by anonymous 24.11.2016 / 09:46

3 answers

2

Use window.location.pathname to get the current Url .

Use Split("/") to split the URL.

The first position indicates dominio , followed by Controller and last Action .

See the result of: console.log(window.location.pathname.split("/"));

    
24.11.2016 / 11:09
1

Alternatively, you can set an ID for each <li> and insert the current class with each controller call. This way, you will not have to worry about which controller is being accessed and the code is simpler to understand and maintain.

    
24.11.2016 / 17:07
1

I usually use the following:

@ViewContext.RouteData.Values["controller"].ToString()
@ViewContext.RouteData.Values["action"].ToString()

See more about ViewContext here .

In addition, you can implement these two Extensions that make the procedure simpler:

public class HtmlExtensions
{
    /// <summary>
    /// Ativa a class no menu à esquerda.
    /// </summary>
    /// <param name="helper"></param>
    /// <param name="Actionvalue"></param>
    /// <param name="Controllervalue">array de controllers.</param>
    /// <returns></returns>
    public static IHtmlString Ativar(this HtmlHelper helper, params string[] Controllervalue)
    {
        var currentController =
            (helper.ViewContext.RequestContext.RouteData.Values["controller"] ?? string.Empty).ToString().UnDash();

        var estaNaController = Controllervalue.Contains(currentController);

        var resultado = estaNaController ? new HtmlString("active") : new HtmlString(string.Empty);
        return resultado;
    }
}

public static class StringExtensions
{
    /// <summary>
    ///    Remover traços ("-") a partir do valor determinado objeto representado como uma cadeia e retorna uma cadeia vazia ( "")
    ///     quando o tipo de instância não poderia ser representado como uma string.
    ///     <para>
    ///         Nota: Isto irá retornar o nome  tipo de determinada instância. Seo runtime type não seja uma string!
    ///     </para>
    /// </summary>
    /// <param name="value">The object instance to undash when represented as its string value.</param>
    /// <returns></returns>
    public static string UnDash(this object value)
    {
        return ((value as string) ?? string.Empty).UnDash();
    }

    /// <summary>
    ///     Removes dashes ("-") from the given string value.
    /// </summary>
    /// <param name="value">The string value that optionally contains dashes.</param>
    /// <returns></returns>
    public static string UnDash(this string value)
    {
        return (value ?? string.Empty).Replace("-", string.Empty);
    }
}

Usage:

<li class="@Html.Ativar("Topico1", "Topico2", "Topico3")">

This is to enable collapsible menus, where the active class is the parent menu.

    
14.12.2016 / 17:08