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,
- Context after authendicated
- List Array need to add a content type
Module flow as below,
- Get all the content type from content type collection
- Here my assumption is list name and content type name is same
- Vola now we have the content type details like Name and ID
- Get the list by Name
- Set ContentTypesEnabled = true.
- Then we can add the content type to the list by Content Type ID
- 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);
}
}
Written by Arivazhagan
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Sharepoint
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#