Reputation: 23
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.
Upvotes: 2
Views: 1324
Reputation: 801
Just put that DropDownList
into the Html.BeginForm
as 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
}
Upvotes: 1