ASP.NET MVC5 - DropDownList with Active Directory Users

asp.net-mvc-5 c# drop-down-menu entity-framework-6

Question

I'm new to ASP.NET MVC, and when I attempted to publish users from Active Directory to my SQL Database, I ran into a problem.

What I have thus far is as follows:

ViewModel:

 public class UserViewModel
{
    public IEnumerable<SelectListItem> myADUsers { get; set; }
    public int SelectedPersonId { get; set; }
}

Controller:

public ActionResult Index()
    {
        UserViewModel myADUsers = new UserViewModel();           
        myADUsers.myADUsers = GetADUsers();

        return View(myADUsers);

    }

public IEnumerable<SelectListItem> GetADUsers()
    {
        List<SelectListItem> _users = new List<SelectListItem>();
        //Instantiate Active Directory Server Connection
        PrincipalContext adServer = new PrincipalContext(ContextType.Domain, null);

        //Instantiate Active Directory User Group
        GroupPrincipal adGroup = GroupPrincipal.FindByIdentity(adServer, "XXXXX");

        if (adGroup != null)
        {
            foreach (Principal p in adGroup.GetMembers())
            {
                _users.Add(new SelectListItem { Text = p.SamAccountName, Value = p.SamAccountName });
            }
        }
        IEnumerable<SelectListItem> myADUsers = _users;

        return myADUsers;
    }

View:

@Html.DropDownList("My AD Users", Model.myADUsers, "Please select a user")

My DropDownList is filled with my Active Directory Users, thus this works well, but how do I retrieve the chosen User?

I would be extremely appreciative of any advice. I'm grateful.

1
2
8/24/2017 7:47:23 AM

Accepted Answer

Put that justDropDownList from theHtml.BeginForm like I shown below:

  @using (Html.BeginForm("Method", "Controller", FormMethod.Post))
    {

    @Html.DropDownList("users", Model.myADUsers, "Please select a user")
<button type="submit">Submit</button>
    }

then add the user's name to your method as follows:

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Method(string users)
{ 
    //do stuff here
}
1
8/24/2017 8:24:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow