【问题标题】:Pass PrincipalSearchResult object to list in ViewModel将 PrincipalSearchResult 对象传递给 ViewModel 中的列表
【发布时间】:2019-06-26 03:32:06
【问题描述】:

我的目标是让用户根据特定条件(名字、姓氏、ID)搜索现有用户的广告并显示匹配的项目。

我正在使用 PrincipalSearcher 来完成此操作:

控制器:

public ViewResult Index(string fname, string lname, int id)
    {
        UserPrincipal user = new UserPrincipal(pcontext);

        user.GivenName = fname;
        user.Surname = lname;
        user.EmployeeId = id.ToString();

        PrincipalSearcher ps = new PrincipalSearcher();
        ps.QueryFilter = user;
        PrincipalSearchResult<Principal> results = ps.FindAll();

        List<Principal> userResults = new List<Principal>();
        foreach (Principal item in results)
        {
            userResults.Add(item);
        }

        var viewModel = new UserSearchViewModel
        {
            Users = userResults.ToList()
        };

        return View(viewModel);
    }

最后,我将结果传递给我创建的视图模型,并将其绑定到列表模型。

视图模型:

    public class UserSearchViewModel
{
    public Request Request { get; set; }

    public List<UserSearch> Users { get; set; }

    public int id { get; set; }

    public string fname { get; set; }

    public string lname { get; set; }
}

我得到的当前错误消息如下: 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”

我尝试将 userResults 更改为 List 类型,但错误仍然存​​在。我尝试只返回结果,但不知道如何提交用户结果,然后在视图中显示结果。

对实现我的目标的任何帮助或指导将不胜感激。

编辑:模型

    public class UserSearch
{
    public int employeeId { get; set; }

    public string firstname { get; set; }

    public string lastname { get; set; }
}

【问题讨论】:

  • UserSearch 类型是你的,对吧?可以展示一下吗?
  • @octavioccl - 我已经添加了模型,真的很基本。
  • 是的,那你需要投影userresult集合,我加个答案

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

您需要将 userresult 投影到您的 UserSearch 模型:

    var viewModel = new UserSearchViewModel
    {
        Users = ps.FindAll().Cast<UserPrincipal>() // You could use also .OfType<UserPrincipal> 
                            .Select(p=>new UserSearch{employeeid=p.EmployeeId,
                                                      firstname=p.GivenName, 
                                                      lastname=p.SurName})
                            .ToList()
    };

在这个post 的帮助下。 Principal 没有名字和姓氏,这就是我做演员的原因

【讨论】:

  • 我更改为 UserPrincipal 而不是 Principal 但随后在 ps.FindAll():Cannot implicitly convert type 'System.DirectoryServices.AccountManagement.PrincipalSearchResult&lt;System.DirectoryServices.AccountManagement.Principal&gt;' to 'System.DirectoryServices.AccountManagement.PrincipalSearchResult&lt;System.DirectoryServices.AccountManagement.UserPrincipal&gt;' 上收到错误消息
猜你喜欢
  • 2020-03-13
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多