Problem converting ContentItem to a custom part

Topics: Writing modules
Sep 6, 2011 at 2:04 AM

I am writing a controller for a testimonials  module and I am have an issue converting a generic ContentItem to a module specific content part.  I am doing a query using the ContentManager which returns IEnumerable<ContentItem>.  My view is passed a ViewModel with a List<TestimonialPart>.  I am trying to manually convert between the two types.  Below is the code:

======================================

 var

testimonials = _contentManager.Query().ForType("TestimonialPart") .List();  

 

testimonialList.Add((TestimonialPart)contentItem);

foreach (ContentItem contentItem in testimonials) {

}

 

var model = new TestimonialListViewModel{

Testimonials = testimonialList

};

 

return View(model);

=====================================

The cast of (TestimonialPart)contentItem gives the following compiler error:

Cannot convert type 'Orchard.ContentManagement.ContentItem' to 'ThorTech.Testimonial.Models.TestimonialPart'

What am I doing wrong?

Thanks!



 

List<TestimonialPart> testimonialList = new List<TestimonialPart >();  

Developer
Sep 6, 2011 at 2:20 AM

Content item cannot be converted to specific content part via casting, as it doesn't inherit from it's parts' types - item is a container holding a collection of parts. Use IContent.As<SomePart>() method to convert item to specific part (it returns a specific part of a given type from the underlying collection).

In your case you'd need to change that line to:

testimonialList.Add(contentItem.As<TestimonialPart>()); 
Sep 6, 2011 at 3:49 AM

Works perfectly.  Thank You!