I see a lot of people coming up against issues trying to get at the fields they have added on their content types. If you can’t figure out how to access the data then read on to discover the important points you need to understand which will make accessing fields easy.
The first important thing to understand is: Fields
are always in a ContentPart
.
The second thing to understand is: If you’re in a class
then you will need to cast the object to dynamic
to get around IntelliSense.
The third thing to understand is: The field name
is a ContentField
type not a string
.
Fields are always in a content part
If it looks like its just in the Fields section of a content type then you need to know what that type is. This is the type not an individual so you are looking for something like Page
or BlogPost
not “About Us”.
This means to access a ProductId
field which has been attached to the Page
content type you would use:
var productId = CurrentContent.ContentItem.Product.ProductId.Value;
Cast to dynamic
The second thing is that if you’re in a class file you will get stuck trying to access anything after the ContentItem
because IntelliSense can’t see the dynamic properties of the class at development time.
It’s simple to access this information, just cast the ContentItem
to a dynamic
type:
var dynamicContentItem = (dynamic)CurrentContent.ContentItem; var itemProductId = dynamicContentItem.Product.ProductId.Value;
The field is a content field type
The last bit is that you don’t just access the value of the field by its name ProductId
because that is a class. If, for example the field type is a “Text Field” then this is actually a class called Orchard.Fields.Fields.InputField
. This class exposes its actual data under the .Value
property.
Other fields types use different methods to access their internal values depending on the type of data they are exposing. Make sure you look at the implementation to figure this out as IntelliSense won’t be available to you so otherwise you won’t notice you have made a mistake until an exception is thrown at run-time.
Sebastien Ros has created an Orchard Cheatsheet which covers common properties that you might want to access on each of the built-in Orchard content fields.
Follow these three simple lessons and you should get the information you need without too much hassle.
No comments :
Post a Comment