Search code examples
javascriptjqueryasp.nethtml-listsactionlink

Get Html.ActionLink parameters from li element with query


I have this unordered list:

     <ul class="list"> 
         <li class="navItem">@Html.ActionLink("Home", "Index", "Home")</li>
         <li class="navItem">@Html.ActionLink("Contact", "ContactForm", "Contact")</li>
     </ul>

and in my script i want to select the li element by his action and controller name, that i can retrieve data like width and position from the specific li element.

my Function looks like this, but i don't know how the selector has to look like.

    function currentItem() {

     //Here i get the current view and controller name
     var actionName = '@ViewContext.RouteData.Values["Action"].ToString()';
     var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()';
     // something like that, putting the link together?
     var $currentItem = $('a[href="' + viewController + controllerName + '"]'); 

     // or find all elements by class name an than do something like
     var myArray = $('.navItem');

     if (myArray[0].Controller == controllerName ||myArray[0].Action == actionName)  {
     $currentItem = myArray[0];
     }

      return $currentItem;
      }

Thanks for helping.

Franhu


Solution

  • First of all lets consider what HTML we will be working with. A Html.ActionLink will convert into an a tag, so your HTML will look something like this:

    <li class="navItem"><a href="/Home/Index">Home</a></li>
    

    With that in mind we can iterate the li elements, check their inner a element and match on the href attribute.

    So something like this should work:

    function currentItem() {
        var actionName = '@ViewContext.RouteData.Values["Action"].ToString()';
        var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()';
    
        var listItems = $('.navItem');
    
        for(var i = 0; i < listItems.length; i++){
            var item = $(listItems[i]);
            var a = item.find("a");
            if(a.attr["href"].indexOf(controllerName + "/" + actionName) != -1){
                return item;
            }
        }
    }
    

    Note that this will return the matching li element. If you want the matching a element then use return a; instead.