Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
This blog post is a contribution from Bharat Rathod, an engineer with the SharePoint Developer Support team.
In this post, I’ll show you how to use UpdateListItems method of the Lists.asmx web service to modify a ListItem which has multi-value people and group column. Most of us tend to fall into trouble while creating the batch element.
Here’s the detailed description of the sample code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;
using Microsoft.SharePoint.SoapServer;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
using (SPSite osite = new SPSite("https://sp/"))
{
using (SPWeb oweb = osite.OpenWeb())
{
SPList mylist = oweb.Lists["TestList"];
SPListItem item = mylist.GetItemById(1);
// Get the user ID of the User whose value needs to be added to the column
SPUser user1 = oweb.AllUsers["contoso\\user1"];
int Id1 = user1.ID;
ListService.Lists list = new ListService.Lists();
list.UseDefaultCredentials = true;
XmlDocument doc = new System.Xml.XmlDocument();
XmlElement batchElement = doc.CreateElement("Batch");
batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");
batchElement.SetAttribute("ViewName", "");
batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" +
"<Field Name='ID'>1</Field>" +
"<Field Name='Title'>Item1</Field>" +
"<Field Name='manyusers'>;#1;#Contoso\\spadmin;#9;#contoso\\user1;#</Field>" +
"</Method>";
try
{
list.UpdateListItems(mylist.ID.ToString(), batchElement);
}
catch (SoapServerException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
One of the most important part of this code is creating the batch element. In order to add users to a multi-value people and group field, we need to get the UserID from the SPWeb object. In the code, I’ve used the following statements:
SPUser user1 = oweb.AllUsers["contoso\\user1"];
int Id1 = user1.ID;
This code finds out the user’s identifier (UserID) of whatever user you want to add to the multi-value field (in this case, it’s contoso\user1).
batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" +
"<Field Name='ID'>1</Field>" +
"<Field Name='Title'>Item1</Field>" +
"<Field Name='manyusers'>;#1;#Contoso\\spadmin;#9;#contoso\\user1;#</Field>" +
"</Method>";
The above code snippet tries to add two users to the column named “manyusers”. Use the ;# symbols before every entity and then end the string with ;# again. One common mistake we tend to do is to miss out on the ;# towards the end of the string.
Try the above sample to get users added to a multi-value people and group field.
Hope this short blog post is of some help!