I had the same question and searched the internet some code examples. I found some code fragments but no easy & complete working solution. So I created this code to do the two steps:
- Get the SspId and TermSetId from a Managed Metadata column in a customin a custom content-type.
- Use this information to execute the GetTermSets method method on the Taxonomy Webservice and parse the result into a usable list list or tree.
- Use the value from the MetadataItem when setting the value for a ListItem
Details:
Step 1.
var clientContext = new ClientContext("https://localhost/sites/STS20120731101501");
var properties = clientContext.GetTaxonomyFieldProperties("MyCustomContentType", "MyManagedMetadataColumn");
string sspId = properties["SspId"]; // e40374fb-a6cc-4854-989f-c1d94a7967ee
string termSetId = properties["TermSetId"]; // 9eeec005-4818-486f-b4d8-bda1d43d42b4
Step 2.
using (var client = new TaxonomywebserviceSoapClient())
{
string sspID = "e40374fb-a6cc-4854-989f-c1d94a7967ee";
string termsetId = "9eeec005-4818-486f-b4d8-bda1d43d42b4";
var items = client.GetMetadataItems(sspID, termsetId);
foreach (var item in items.AsTree())
{
Console.WriteLine(new string(' ', item.Level) + item);
}
var firstMetadataItem = items.First(); // Just take the first as an example.
}
The extension methods : GetTaxonomyFieldProperties, GetMetadataItems and
AsTreeStep 3. can be found here.
using (var clientContext = new ClientContext("https://localhost/sites/STS20120731101501"))
{
var list = clientContext.Web.Lists.GetByTitle("MyList");
var newListItem = list.AddItem(new ListItemCreationInformation());
newListItem["SomeNormalField"] = "SomeText";
newListItem["MyManagedMetadataColumn"] = firstMetadataItem.ToString(); // This will be like "MyFirstValue|643b827f-5fed-4a34-8270-ed0c662df639"
newListItem.Update();
clientContext.ExecuteQuery();
}
The extension methods : **GetTaxonomyFieldProperties**, **GetMetadataItems** and **AsTree** can be found [here][1].
References