Retrieving a Filed of contenttype

Topics: General
Dec 18, 2012 at 9:31 AM

Hi

i am new to orchard. I don't know how to retrieve a field of a contenttype (not the field of a part).

Developer
Dec 18, 2012 at 9:46 AM

Fields are never attached to content types, always to content parts, even though it may look like it's possible when you do this via the admin. However, what really happens is that Orchard creates a content part with the same name as the content type, and attaches the field to that content part.

So, to retrieve that content field, you will have to access it via the content part. For example, if you have a content type called "Book" to which you added a text field called "Author" via the admin, Orchard will have created a content part called "Book" which has a field called "Author".

To access that field from code, you will do something like this:

@{
   // If we're in a content part template, we can access the content item via the Model.ContentItem property.
   var contentItem = Model.ContentItem;

   // We can access all parts and their fields when starting from the content item (be sure it's typed as dynamic to take advantage of the dot syntax instead of having to use LINQ statements)
   // Syntaxt: [contentItem].[contentPart].[contentField].[fieldProperty e.g. Value]
   var author = contentItem.Book.Author.Value;
}
Dec 18, 2012 at 10:37 AM
Edited Dec 18, 2012 at 10:37 AM

Thanks a lot. It really helped.