Last Updated: February 25, 2016
·
1.063K
· arivazhagan

Add Contentype to a list by ContentType Name [Quick Dirty tip]

Today i have a situation to add the content type to a list on the fly so as the list get created i need to add exisiting content type to the list, I did a little research, but all are pointing to update content ype by ID. so i here is a snippet i used to handle the situation. I know its not prefect but it will do the trick.

Lets break down the code, Here my parameters,

  1. Context after authendicated
  2. List Array need to add a content type

Module flow as below,

  1. Get all the content type from content type collection
  2. Here my assumption is list name and content type name is same
  3. Vola now we have the content type details like Name and ID
  4. Get the list by Name
  5. Set ContentTypesEnabled = true.
  6. Then we can add the content type to the list by Content Type ID
  7. context.ExecuteQuery()

There you go the list is updated with content type by name, Feel free to give your comments and suggestions.

public void setListContentType(ClientContext context, String listArray)
{
    Web web = context.Web;
    try
    {
        dynamic listJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(listArray);
        foreach (var lstItem in listJSON)
        {
            ContentTypeCollection sitContType = web.ContentTypes;
            context.Load(sitContType);
            context.ExecuteQuery();
            foreach (ContentType ctype in sitContType)
            {
                if (lstItem.Name == ctype.Name)
                {
                    Console.WriteLine("Available Cont Type: " + ctype.Name+" ID : "+ctype.Id);
                    ContentType ct = context.Web.ContentTypes.GetById(ctype.Id.ToString());
                    List lst = context.Web.Lists.GetByTitle(lstItem.Name.ToString());
                    lst.ContentTypesEnabled = true;
                    lst.ContentTypes.AddExistingContentType(ct);
                }
            }
            context.ExecuteQuery();
            Console.WriteLine(lstItem.Name+" list content type is updated");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Something went wrong in setListContentType Module : " + e);
    }
}