ASP.NET MVC5 - DropDownList with Active Directory Users

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

Question

I am new to ASP.NET MVC and I got stuck when I try to post Users from Active Directory to my SQL Database.

This is what I got so far:

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")

This works fine, as my DropDownList is populated with my Users from Active Directory but how do I get the selected User?

I'd be very grateful to get some tipps.. Thank you.

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

Accepted Answer

Just put that DropDownList into the Html.BeginFormas I did this below:

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

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

And then receive the user's name in your method like this:

[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