Search code examples
htmlasp.net-mvc-5dropdown

MVC 5 bootstrap dropdown with dynamic anchors


i want to add li elements to this bootstrap dropdown from database

     <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>

                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Apps<b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">App 1</a></li>
                        <li><a href="#">App 2</a></li>
                        <li><a href="#">App 3</a></li>            
                    </ul>
                </li>
            </ul>
        </div>

The objective is to populate the anchor with a path for a different application so user can redirect to applications it has access to. Although, I'm not sure how can i populate this.

Note. It is possible to be more apps because Administrators will be able to add more apps for users to access in database


Solution

  • Imagine your application model is

    public class App
    {
        public string Url { get; set; }
    
        public string Name { get; set; }
    }
    

    And you passed application collection as List<App> you can do the following

    <ul class="dropdown-menu">
        @foreach (App app in Model.Applications)
        {
            <li><a href="@app.Url">@app.Name</a></li>
        }
    </ul>