Select the Controller name via Javascript

Asked

Viewed 179 times

1

I have the code below and would like to add to class="current" to <li></li> according to the controller I am 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 controller/action in the view?

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

3 answers

2


Use window.location.pathname to obtain the Url chain.

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

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

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

inserir a descrição da imagem aqui

1

Alternatively, you can set an ID for each <li> and insert the Current class at each controller call. This way, you won’t have to worry about which controller is being accessed and the code is easier to understand and maintain.

1

I usually use the following:

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

See more about ViewContext here.

Additionally, you can implement these two Extensions which 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);
    }
}

Use:

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

Serves to activate menus Collapsible, where the active class is the parent menu.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.