使用客户端对象模型将用户添加到UserMulti字段类型

3
我有点像SharePoint新手,所以请耐心等待。我需要使用客户端对象模型在我们的自定义列表中创建一个新的列表项。我一直在按照MSDN网站上描述的示例进行操作,大部分情况下都能成功。我们有一个包含多个字段的列表,其中包括一个UserMulti字段类型。我在向此字段添加用户时遇到了问题。到目前为止,我尝试了以下方法,但这似乎总是默认为系统帐户,而不是字段中指定的用户。
   ...
   listItem["ProjectMembers"] = "1;#domain\\johndoe";
   listItem.Update();
   _clientContext.ExecuteQuery();

我需要先进行某种类型的查找吗?感谢您的帮助。谢谢。

2个回答

6

花了一些时间,但最终我找到了解决方法。以下是两种可行的方法:

  1. Assign a Principal to the list item

        var principal = _rootWeb.EnsureUser("domain\\johndoe") as Principal;
        listItem["ProjectMembers"] = principal;
        listItem.Update();
        _clientContext.ExecuteQuery();
    
  2. Assign an list of FieldUserValue if you need to assign more than one user to the field.

        string[] users = { "domain\\johndoe", "domain\\peterpan" };
        var projectMembers = users
            .Select(loginName => FieldUserValue.FromUser(loginName))
            .ToList();
    
        listItem["ProjectMembers"] = projectMembers;
        listItem.Update();
        _clientContext.ExecuteQuery();
    

我相信有更好的方法来做这件事,你可以将两种方法结合起来,以确保在将用户添加到列表之前他们是有效的,但是目前这种方法已经有效了。希望这能对其他人有所帮助。


0

微软有一篇维基文章,名为“SharePoint: A Complete Guide to Getting and Setting Fields using C#”,可以提供帮助。http://social.technet.microsoft.com/wiki/contents/articles/21801.sharepoint-a-complete-guide-to-getting-and-setting-fields-using-c.aspx#Set_and_Get_a_Multi-Person_Field

其中包括以下示例代码。

var lotsofpeople = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
var personA = web.EnsureUser("contoso\\fred");
var personAValue = new SPFieldUserValue(web, personA.ID, personA.LoginName);
var personB = web.EnsureUser("contoso\\barnie");
var personBValue = new SPFieldUserValue(web, personB.ID, personB.LoginName);
lotsofpeople.Add(personAValue);
lotsofpeople.Add(personBValue);
item["lotsofpeoplefield"] = lotsofpeople;
item.Update();

这不是 OP 所要求的 CSOM。 - Colin Gardner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接