Bind drop down list inside cshtm with server side

2019-08-29 07:13发布

I have users list and want to bind that on top navigation bar, this will always visible for many pages, how i can bind it, i don't want to add code on each file, is there any method in mvc4 that is called for each view?

My view:

<div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Name Three<b class="caret"></b></a>
                        <ul class="dropdown-menu">
//Here i want to show data dynamically, data can be in collection.
                            <li><a href="#">Name one</a></li>
                            <li><a href="#">Name two</a></li>
                            <li><a href="#">Name Three</a></li>
                            <li><a href="#">Four</a></li>
                        </ul>
                    </li>
                </ul>
            </div>

Controller:

ICollection<Names> names = this.obj.GetNames();

1条回答
疯言疯语
2楼-- · 2019-08-29 07:33

In situations like this I prefer to use a code behind call to the view bag. try something like this

@Html.DropDownList("Action", PathToController.GetUsers())

then on the controller where you want to put this method

public static List<SelectListItem> GetUsers(){
    List<SelectListItem> ls = new List<SelectListItem>();
    var result = //database call here
    foreach(var temp in result){
        ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.ID });
    }
    return ls;
}
查看更多
登录 后发表回答