Kasra
Kasra

Reputation: 59

.NET How to search and get list of users in Active Directory

I've never programmed against Active directory, and MVC before and need some advice.

I'm using following code to search, and get list of users in a view. I don't know if I'm on the right track, and how do I get it in a list view on cshtml?

   public ActionResult Find()
    {
        DirectoryEntry entry = new DirectoryEntry(
                      "LDAP://example..");

        DirectorySearcher searcher;
        SearchResultCollection results;

        searcher = new DirectorySearcher(entry);

        searcher.Filter = "(&(objectClass=user)(displayname=*))";
        searcher.SearchScope = SearchScope.Subtree;

        using (searcher)
        {
            results = searcher.FindAll();

            foreach (SearchResult result in results)
            {
               string searchOK = result.Properties["displayname"][0].ToString();
               objects.Add(searchOK);
            }
        }
        return View();
    }

Upvotes: 1

Views: 1793

Answers (1)

Marc
Marc

Reputation: 3959

Just pass the list of users to the View:

return View(objects);

In your View, declare the type of your model on the top like this:

@model List<string>

And then you can access the list using the @Model Variable anywhere in your View.

Upvotes: 5

Related Questions