This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void SetManagedMetaDataField(string siteUrl, | |
string listName, | |
string itemID, | |
string fieldName, | |
string term) | |
{ | |
ClientContext clientContext = new ClientContext(siteUrl); | |
List list = clientContext.Web.Lists.GetByTitle(listName); | |
FieldCollection fields = list.Fields; | |
Field field = fields.GetByInternalNameOrTitle(fieldName); | |
CamlQuery camlQueryForItem = new CamlQuery(); | |
string queryXml = @"<view> | |
<query> | |
<where> | |
<eq> | |
<fieldref name="ID"> | |
<value type="Counter">!@itemid</value> | |
</fieldref></eq> | |
</where> | |
</query> | |
</view>"; | |
camlQueryForItem.ViewXml = queryXml.Replace("!@itemid", itemID); | |
ListItemCollection listItems = list.GetItems(camlQueryForItem); | |
clientContext.Load(listItems, items =>; items.Include(i =>; i[fieldName])); | |
clientContext.Load(fields); | |
clientContext.Load(field); | |
clientContext.ExecuteQuery(); | |
TaxonomyField txField = clientContext.CastTo<taxonomyfield>(field); | |
string termId = GetTermIdForTerm(term, txField.TermSetId, clientContext); | |
ListItem item = listItems[0]; | |
TaxonomyFieldValueCollection termValues = null; | |
TaxonomyFieldValue termValue = null; | |
string termValueString = string.Empty; | |
if (txField.AllowMultipleValues) | |
{ | |
termValues = item[fieldName] as TaxonomyFieldValueCollection; | |
foreach (TaxonomyFieldValue tv in termValues) | |
{ | |
termValueString += tv.WssId + ";#" + tv.Label + "|" + tv.TermGuid + ";#"; | |
} | |
termValueString += "-1;#" + term + "|" + termId; | |
termValues = new TaxonomyFieldValueCollection(clientContext, termValueString, txField); | |
txField.SetFieldValueByValueCollection(item,termValues); | |
} | |
else | |
{ | |
termValue = new TaxonomyFieldValue(); | |
termValue.Label = term; | |
termValue.TermGuid = termId; | |
termValue.WssId = -1; | |
txField.SetFieldValueByValue(item, termValue); | |
} | |
item.Update(); | |
clientContext.Load(item); | |
clientContext.ExecuteQuery(); | |
} |