如何在ASP.NET Core中使用Active Directory组的成员填充下拉列表?

时间:2019-04-25 07:49:14

标签: c# asp.net asp.net-core

我想用Active Directory组中成员的姓名填充一个下拉列表。我现在能做的就是显示Microsoft.AspNetCore.Mvc.Rendering.SelectListItem,所以某处出了问题。

这是我到目前为止所拥有的:

public static List<SelectListItem> ManagementUsers = GetManagementUsers();

public static List<SelectListItem> GetManagementUsers()
{
    List<SelectListItem> _users = new List<SelectListItem>();
    PrincipalContext adServer = new PrincipalContext(ContextType.Domain, "DOMAIN");

    GroupPrincipal managerGroup = GroupPrincipal.FindByIdentity(adServer, "Management Group");

    if (managerGroup != null)
    {
        foreach (Principal principal in managerGroup.GetMembers())
        {
            _users.Add(new SelectListItem { Text = principal.SamAccountName, Value = principal.SamAccountName });
        }
    }

    List<SelectListItem> ManagementUsers = _users;

    return ManagementUsers;
}

然后在我的剃刀页面上:

<select id="manager" class="form-control form-control-sm" asp-items="@(new SelectList(IndexModel.ManagementUsers))">
    <option value=""></option>
</select>

1 个答案:

答案 0 :(得分:1)

在您的剃须刀页面中,更改为使用以下代码:

<select id="manager" class="form-control form-control-sm" asp-items="@((List<SelectListItem>)IndexModel.ManagementUsers)">
    <option value=""></option>
</select>

按照@poke的建议,您可以直接使用asp-items="@IndexModel.ManagementUsers"