Search code examples
asp.net-mvcdrop-down-menuactioncontrollers

Find list of Controllers Name and Actions Name in mvc


i have a navigation page and i wanna that when click on create navigation i show dropdown that include of Controllers name and when choose one controller then in another dropdown show related action

so how can i find my controllers name and action ?


Solution

  • I did do the heavy lifting for the controllers and actions. This code generates an unordered list with list items and can be dropped in your view. You can use your favorite jquery menu plugin that turns this list into a menu with the desired effect.

    This code can be easily refactored to a solution where a controller and a (partial)view is used in case you need to reuse this snippet.

    <ul>
    @{
        var allTypes = 
                from asm 
                in AppDomain.CurrentDomain.GetAssemblies()
                let types = (
                    from type 
                    in asm.GetTypes()
                    let contname = type.Name.Replace("Controller","")
                    let methods = (
                        from method 
                        in type.GetMethods()
                        let hasHttpPost =
                            method.GetCustomAttributes(
                                typeof(HttpPostAttribute),
                                false).Length > 0
                        where (method.ReturnType.IsSubclassOf(
                                        typeof(ActionResult))
                        || method.ReturnType == typeof(ActionResult))
                        && !hasHttpPost
                        select new
                        {
                            Controller = contname,
                            Action = method.Name
                        }
                    )
                    where type.IsSubclassOf(typeof(Controller))
                    select new {Name = contname, Controllers = methods }
                    )
                select new { asm.FullName, AllControllers = types };
    
    
        foreach (var controllers in allTypes)
        {
            foreach (var controller in controllers.AllControllers)
            {
                <li>
                @controller.Name
                <ul>
                @{
                foreach (var controlleraction in controller.Controllers)
                {
                  <li>
                    <a href="@controlleraction.Controller/@controlleraction.Action">
                      @controlleraction.Action
                    </a>
                  </li>
                }
                }
                </ul>
                </li>
            }
        }
    }
    </ul>