ASP.NET MVC dropdownlist

后端 未结 4 1073
后悔当初
后悔当初 2021-02-06 09:35

Can someone point me to an article that shows the dropdownlist being populated from linq to sql (text and value being set).

Thanks Danny

4条回答
  •  醉酒成梦
    2021-02-06 10:30

    Write in the view:

    @{
    TaskManagerContext context = new TaskManagerContext();
    
    IEnumerable CDrop = context.Users.ToList();
    List selectList = new List();
    foreach (var c in CDrop)
    {
        SelectListItem i = new SelectListItem();
        i.Text = c.Username.ToString();
        i.Value = c.ID.ToString();
        selectList.Add(i);
    }
    

    }

    You can reference it ike that:

    @Html.DropDownListFor(m => m.UserID,
                              new SelectList(selectList, "Value", "Text"));
    

    You can also choose a specific row:

    TaskManagerContext context = new TaskManagerContext();
    UsersRepository repo = new UsersRepository();
    User user = repo.GetAll().FirstOrDefault(u => u.ID == ViewBag.UserId);
    ViewBag.User = user;
    
    

    @ViewBag.User.Username

提交回复
热议问题