1

I wrote a C# function that retries a list of users from Active Directory.

        public static IEnumerable<string> ActiveDirectoryUsersList()
        {
            string[] adPropertiesToRetrive = { "displayName", "mail", "telephoneNumber", "displayName", "mobile" };
            List<string> usersInfo = new List<string>();
            // create and return new LDAP connection with desired settings  
            DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://OU=Users,OU=OUName,OU=Groups,DC=myDomain,DC=com", null, null, AuthenticationTypes.Secure);

            DirectorySearcher search = new DirectorySearcher(myLdapConnection);
            search.Filter = "(&(objectClass=user)(objectCategory=person))";
            foreach (var prop in adPropertiesToRetrive)
            {
                search.PropertiesToLoad.Add(prop);
            }

            SearchResultCollection allUsers = search.FindAll();

            foreach (SearchResult user in allUsers)
            {
                foreach (var prop in adPropertiesToRetrive)
                {
                    var val = user.Properties[prop].Count > 0 ? user.Properties[prop][0].ToString() : "-";
                    usersInfo.Add(val);

                }

            }
            return usersInfo;
        }

now I want to use this in my Razor function and iterate something like this:

@foreach (var user in Fucntion("Custom.ActiveDirectoryUsersList"))
{
    @user
}

but the result of Function(string Name) is an HTML string result. How can i call upon the inline C# function defined to get the raw result of the function?

Mortalus
  • 10,574
  • 11
  • 67
  • 117

2 Answers2

0
@foreach (var user in Function("Custom.ActiveDirectoryUsersList"))
{
   <text>@Html.Raw(user)</text>
}

could do the trick?

Alfred Severo
  • 496
  • 5
  • 15
0

The Function-method in a Razor Page is designed for outputting Html so that's why its behaving the way it is. If you want to retrieve any non-html value from your function, you can use the Functions.ExecuteFunction(...) helper method, which returns an object which you can then cast to the type you know your function is returning.

So all in all would your code look like this

@foreach (var user in ((IEnumerable<string>)Functions.ExecuteFunction("Custom.ActiveDirectoryUsersList")))
{
  <span>@user</span>
}

Or a bit cleaner

@{
  var users = (IEnumerable<string>)Functions.ExecuteFunction("Custom.ActiveDirectoryUsersList");

  foreach (var user in users)
  {
    <span>@user</span>
  }
}

Read about the Functions helper class here

Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48