Reputation: 2395
I'm using Umbraco's ModelsBuilder to generate strongly typed models from my document types to use in my code.
This is working pretty well but I want to know how I can get strongly typed objects for the children of any given generated model.
Here is an example:
public ActionResult Index(HomePage model)
{
var components = model
.Children.Where(x => x.DocumentTypeAlias == PageComponentsFolder.ModelTypeAlias)
.Single().Children;
}
HomePage is a strongly typed class generated by the Umbraco model builder. Under the home page node I have a page components folder with several other nodes that all inherit from a ComponentsBaseClass.
How can I make my components variable above a strongly typed list of objects.
Is this possible?
Upvotes: 1
Views: 1723
Reputation: 2395
Ok this is what I ended up with in the end, here is an example of how to use strongly typed models generated by the Umbraco model binder.
var components = model.Children
.Where(x => x.DocumentTypeAlias == PageComponentsFolder.ModelTypeAlias)
.Single().Children;
foreach (var component in components)
{
string componentNodeTypeAlias = component.DocumentTypeAlias;
switch (componentNodeTypeAlias)
{
case SimpleHero.ModelTypeAlias:
Html.Partial("component_simpleHero", component as SimpleHero)
break;
case VideoWithHtml.ModelTypeAlias:
Html.Partial("component_videoWithHTML", component as VideoWithHtml)
break;
}
}
Upvotes: 0
Reputation: 547
You can target children of a specific type in Umbraco like this:
IEnumerable<YourModel> childrenOfType = model.Children<YourModel>();
That will return all children of the model with the type YourModel
— it essentially combines a Where()
and a Cast<T>()
To answer your question of "is this possible", the answer is no.
You can't have the kind of "strongly typed list of objects" that you are after because in C# a list (or other IEnumerable) is always a list of a common type e.g. List<ACommonType>
. In the case of Umbraco they all share an interface of IPublishedContent
. You can iterate through that list and work out the actual type of each object. In Umbraco the IPublishedContent in the list do not actually use the types from the ModelsBuilder until you cast them.
foreach(IPublishedContent c in collectionOfIPublishedContent)
{
// basic if
if (c.DocumentTypeAlias == YourModel.ModelTypeAlias)
{
YourModel stronglyTypedContent = c as YourModel;
// do some stuff
}
// or switch...
switch (c.DocumentTypeAlias)
{
case YourModel.ModelTypeAlias:
YourModel stronglyTypedContent2 = c as YourModel;
// do a thing
break;
}
// or use implicit casts with null checking
YourModel stronglyTypedContent3 = c as YourModel;
if (stronglyTypedContent3 != null)
{
// congrats, your content is of the type YourModel
}
}
Upvotes: 1