Add Contentype in SharePoint 2013 using c# [CSOM]
Adding a contentype in sharepoint is little trickey for me at the first i cant quite understand it, as always microsoft documentation is really sucks and not complete and so and so.
Code speaks louder than works, so here you go,
public void addContentType(ClientContext context, Web web, String cntTypes)
{
dynamic cntJSON = Newtonsoft.Json.JsonConvert.DeserializeObject(cntTypes);
foreach (var ctItem in cntJSON)
{
ContentTypeCollection ContType = web.ContentTypes;
ContentTypeCreationInformation msnContType = new ContentTypeCreationInformation();
msnContType.Name = ctItem.Name;
msnContType.Description = ctItem.Description;
msnContType.Group = ctItem.Group;
if (ctItem.Type == "docset")
{
msnContType.ParentContentType = web.ContentTypes.GetById("0x0120D520");
}
ContentType newCntType = ContType.Add(msnContType);
context.ExecuteQuery();
web.Update();
Console.WriteLine(ctItem.Name + " content type created successfully");
}
}
}
let me break it down the process for you,
-
ContentTypeCollection - Holds site content Type collection as below
ContentTypeCollection siteContType = web.ContentTypes;
ContentTypeCreationInformation - Holds the newly creating content type information like name,description and other properties.
-
create new content type with ContentTypeCreationInformation as below
ContentTypeCreationInformation newContType = new ContentTypeCreationInformation();
-
Then add the required properties as below,
msnContType.Name = "IronMan"; msnContType.Description = "Tony Stark Inc."; msnContType.Group = "Super Heros";
-
If you want to create docset content type you need to add the ParentContentType as below,
newContType.ParentContentType = web.ContentTypes.GetById("0x0120D520");
FYI 0x0120D520 is the id of docset contenttype.
-
Add newly created contentype to site content type collection as below
ContentType newCntType = ContType.Add(msnContType);
-
Save your changes,
context.ExecuteQuery(); web.Update();
Feel free to share if you think there is a better way to add content types.