views:

2982

answers:

3

Hi,

I got a question regarding content types and their IDs and how to use them with the object model.

First of all, I defined some site columns, a content type using these columns and a list definition using this content type via CAML. Each of the three components is realized as a feature. Another feature creates a list instance of this list definition.

So when I try to add a new item to the list using the my content type I use the following code.

 SPListItem listItem = list.Items.Add();
 SPContentType type = list.ContentTypes[new ContentTypeId("0x010044fb4458c2eb4800825910845a35554c")];
 listItem["ContentTypeId"] = type.Id;
 listItem["Title"] = "Titel";
 listItem.Update();

When I execute this piece of code the type object is still null, also I'm sure the content type is attached to the list. Debugging the code and inspecting the list's content types shows me that the content type attached to the list doesn't have the id I defined in the content type definition (CAML). The id within the list instance is different but starts with the one I defined in the content type definition. 0x010044FB4458C2EB4800825910845A35554C0077D683BDD9969F4E920A27C334463321

So is this behavior normal? I expected the content type attached to the list to have the same id as in the definition.

My main goal is avoiding to use the name of the content type to retrieve it from the list's content types, but to use the unique id.

bye Flo

+5  A: 

When you create a list based on a content type, each instance of the list is actually a new content type that inherits from the parent.

Take a look at this... http://soerennielsen.wordpress.com/2007/09/11/propagate-site-content-types-to-list-content-types/

Update-Regarding finding the instance of the List without using the name, take a look at the SPContentTypeUsage class also!

routeNpingme
+1  A: 

Don't stress too much about coding the Content Type's name as a constant within your code. While at first glance it may seem that it is possible to change the name of the content type, it should be regarded as a constant because the implications of changing the content type's name are non-trivial enough to demand a full build and re-release of your solution, allowing a change of the coded constant.

Nat
+1  A: 

The ContentTypeID on the list is the ContentTypeID + the list ID.

The following code should do the trick:

//i try and keep these in a string constants class to avoid 
//having to manage "magic strings" throughout my solution
SPContentTypeID ctid = new ContentTypeId("0x010044fb4458c2eb4800825910845a35554c");


//here's the magic
SPContentTypeID listCTID = list.ContentTypes.BestMatch(ctid);


//retrieve the ContentType with the appropriate ID
SPContentType type = list.ContentTypes[listCTID]; 


//do your thing    
SPListItem listItem = list.Items.Add(); 
listItem["ContentTypeId"] = type.Id; 
listItem["Title"] = "Titel"; 
listItem.Update();
Jason