c# - ASP.NET MVC5 - 带有 Active Directory 用户的 DropDownList

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

我是 ASP.NET MVC 的新手,当我尝试将用户从 Active Directory 发布到我的 SQL 数据库时遇到了困难。

这是我到目前为止得到的:

View 模型:

 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;
    }

查看:

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

这很好用,因为我的 DropDownList 中填充了我来自 Active Directory 的用户,但我如何获得选定的用户?

如果能得到一些小费,我将不胜感激。谢谢。

最佳答案

只需将 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
}

关于c# - ASP.NET MVC5 - 带有 Active Directory 用户的 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45855835/

相关文章:

flutter - 将数据从MySQL数据库填充到Flutter中的DropDown

javascript - 受 jquery.selectBox 插件影响的表单选择框的更改值

c# - 无法使用代码优先创建数据库

c# - 保存具有多个父项的 EF 实例

c# - 为什么 DirectoryInfo.GetFiles() 匹配与掩码不匹配的文件?

C#:如何访问窗体类外部的按钮

c# - C# 结构与元组中的值语义

c# - 使用不带 ViewSortHintAttribute 的通用 View 模型进行 Prism 区域排序

c# - 如何将gridview与来自两个不同表的数据绑定(bind)C#

c# - 在 C# 中使用通用存储库时连接多个表