在 MVC 视图中显示 Active Directory 组

Display Active Directory Group in a MVC view

我正在尝试在视图中显示活动目录组成员。当我 运行 代码时,我遇到了错误 "The model item passed into the dictionary is of type 'System.String[]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[SSSFT.LogIT.Models.ActiveDirectory]'"。调试代码显示我正在寻找的所有组成员

型号Class

public class ActiveDirectory
{
    public int id { get; set; }

    //public string Username { get; set; }

    //public string Email { get; set; }

    public string SamAccountName { get; set; }


}

控制器

   public ActionResult Index(string username)
    {
        username = "sssftappdev";
        string[]output = null;     
        using (var ctx = new PrincipalContext(ContextType.Domain))
        using (var user = UserPrincipal.FindByIdentity(ctx, username))
        {
            if (user != null)
            {
                output = user.GetGroups() //this returns a collection of principal objects
                    .Select(x => x.SamAccountName) // select the name.  you may change this to choose the display name or whatever you want
                    .ToArray(); // convert to string array
            }

        }
       return View(output);
    }

查看

@model IEnumerable<SSSFT.LogIT.Models.ActiveDirectory>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.SamAccountName)
    </th>
    <th></th>
</tr>

 @foreach (var item in Model) {
  <tr>
    <td>
        @Html.DisplayFor(modelItem => item.SamAccountName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
        @Html.ActionLink("Details", "Details", new { id=item.id }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.id })
    </td>
   </tr>
 }

  </table>

您只需更新您的@model 即可修复此错误:

@model String[]

您目前正在将 String[] 传递给您的视图,同时期望 SSSFT.LogIT.Models.ActiveDirectory 的 IEnumerable。将您的代码更新为 return 正确的数据类型,或者根据您 return.

的实际结果调整您的强类型视图