我是ASP.NET MVC的新手,当我尝试将用户从Active Directory发布到我的SQL数据库时,我遇到了困难。
这是我到目前为止所得到的:
视图模型:
public class UserViewModel
{
public IEnumerable<SelectListItem> myADUsers { get; set; }
public int SelectedPersonId { get; set; }
}
控制器:
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;
}
查看:
@Html.DropDownList("My AD Users", Model.myADUsers, "Please select a user")
这样可以正常工作,因为我的DropDownList是使用Active Directory中的用户填充的,但我如何获取所选用户?
我非常感谢能得到一些东西..谢谢你。
答案 0 :(得分:1)
只需将DropDownList
放入Html.BeginForm
,就像我在下面所做的那样:
@using (Html.BeginForm("Method", "Controller", FormMethod.Post))
{
@Html.DropDownList("users", Model.myADUsers, "Please select a user")
<button type="submit">Submit</button>
}
然后在您的方法中接收用户名,如下所示:
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Method(string users)
{
//do stuff here
}