How to get the multi taxonomy field values for an item using Client Side Object Model in SharePoint 2013



I have a custom list named Custom in the SharePoint 2013 site. Custom list has the following columns.

Ø  Title – Single line of text

Ø  Metadata – Managed Metadata (Allow Multiple Values is enabled)

I have added an item which has the following value

Ø  Title – Test

Ø  Metadata – Term1;Term2;

In this blog you will see how to get the Metadata column values for the item from Custom list using Client Side Object Model in SharePoint 2013.

 Steps Involved:

1.       Open Visual Studio 2012 (Run as administrator).

2.       Go to File=> New => Project.

3.       Select Console Application in the Visual C# node from the installed templates.

4.       Enter the Name and click on Ok.

5.       In the solution explorer, right click on References folder and then click on Add Reference.

6.       Add the following assemblies from 15 hive (C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI).

a.       Microsoft.SharePoint.Client.dll

b.      Microsoft.SharePoint.Client.Runtime.dll

c.       Microsoft.SharePoint.Client.Taxonomy.dll

7.       Open Program.cs file and replace the code with the following


 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.SharePoint.Client;

using Microsoft.SharePoint.Client.Taxonomy;

using System.Collections.ObjectModel;

 

namespace ManagedMetadataClient

{

    class Program

    {

        static void Main(string[] args)

        {

            // ClienContext - Get the context for the SharePoint Site

            // SharePoint site URL - http://c4968397007/

            ClientContext clientContext = new ClientContext("http://c4968397007/");

 

            // SharePoint web

            Web web = clientContext.Web;

 

            // Get the list using Title

            List list = web.Lists.GetByTitle("Custom");

 

            // Get the list item by id

            ListItem item = list.GetItemById(2);

            clientContext.Load(item);

 

            // Execute the query to the server

            clientContext.ExecuteQuery();

 

            // Taxonomy field value

            TaxonomyFieldValueCollection taxFieldValueColl = item["Metadata"] as TaxonomyFieldValueCollection;

 

            // Loop through all the taxonomy field values

            foreach (TaxonomyFieldValue taxFieldValue in taxFieldValueColl)

            {

                // Display the taxonomy field value

                Console.WriteLine(taxFieldValue.Label);

            }

            Console.ReadLine();               

        }

    }

}

 
Output: Term1 & Term2 will be the output.