Populating ASP.NET MVC DropDownList

2019-01-16 14:17发布

OK, I've been Googling for hours and trying everything and can't get anything to work. I am learning MVC using Sharp Architecture and have generated some basic forms for creating Client objects. I want to fill the state drop down list with a list of US states and let the user pick from that list. I am able to populate the list and get the value back (to save the client) but when I go to edit the client, the client's current state is not selected. I have set the selected value in the SelectList:

<li>
    <label for="Client_StateProvince">StateProvince:</label>
    <div>
        <%= Html.DropDownListFor(c=>c.Client.StateProvince, new SelectList(Model.StateProvinces, "id", "Name", Model.Client.StateProvince), "-- Select State --")%>
    </div>
    <%= Html.ValidationMessage("Client.StateProvince")%>
</li>

This does not seem to be good enough. What am I missing?

7条回答
一夜七次
2楼-- · 2019-01-16 14:47
public ActionResult  AllUsers()
{
    List<Users> users = userRep.GetUsers();
    var listUsers = (from u in users.AsEnumerable()
                     select new SelectListItem
                     {
                        Text = u.UserName,
                        Value = u.UserId.ToString(),
                        Selected = (u.UserId==6)
                     }).AsEnumerable();
    ViewBag.ListItems = listUsers;
    //ViewBag.SelectedItem = 2;
    return View();
}

In AllUsers.cshtml

<p>@Html.DropDownList("ListItems")</p>
查看更多
登录 后发表回答