2

In a DXA View I have a Component Link field that can link to an Image or a Content Component.

While looping through the Components in the Component Link field, I want to know if it is an Image or what type of Component is in the list, and then call the render the relevant View. How is this possible?

I'm using code like this:

foreach (var component in Model.Content_components)
{            
     <li>component.Title</li> 
}
2

You can map the different CM Schemas to different View Model types and let your Content_components property use a common base class (can be abstract base classEntityModel). See, for example, Abstract model property mapping throws exception

If you iterate over the items in the list, you will find that each item will have a concrete sublass, depending on the CM Schema of the linked Component. So, you can test on component.GetType() or using if (component is Image) to determine how to render the linked Entity Model. You can then use @Html.DxaEntity(component, "<ViewName>") to render each item with an appropriate Entity View.

  • Thank you Rick for the nice tips. Great idea on using if (component is Image). Thanks! – robrtc Sep 22 '17 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.