Access user created field dynamically

Topics: Customizing Orchard
Nov 18, 2012 at 6:38 PM
Edited Nov 18, 2012 at 11:28 PM

Hi guys,

I need your advice how to deal with dynamic stuff. I can access a user created field in dynamic fashion like this

var dfield = ((dynamic)content).Decision.FieldName;
with content type and field name hard coded in the statement.

But is there any way to access it if I know content type and field name in runtime only?

Developer
Dec 18, 2012 at 12:32 PM

You can use Lambda's to query parts and fields when you know their names only at runtime. A ContentItem has a Parts collection, and each Part in turn has a Fields collection. This means you can do something like this:

var contentItem = (ContentItem)Model.ContentItem;
var partName = "MyPart";
var fieldName = "MyField";
var field = contentItem.Parts.Single(p => p.PartDefinition.Name == partName).Fields.Single(f => f.Name == fieldName);