Check if Part has a field before displaying

Topics: Writing themes
Jan 25, 2014 at 9:16 PM
Wondering if someone can help me figure this out.

I attached a MediaLIbraryPickerField to the BlogPost part to use as a blog thumbnail in a theme. It works great, except it requires anyone who uses the theme to do the same or they get a:
'Orchard.Blogs.Models.BlogPostPart' does not contain a definition for 'BlogPostImage'
error message.

Is there a way in the View file to check if the field exists before attempting to display the media url?

I'm referencing the media parts using post.ContentItem.BlogPostPart.BlogPostImage.MediaParts where post has been cast as dynamic.

Let me know if I need to provide any more information for suggestions, and as always, thanks for any assistance.
Jan 26, 2014 at 9:20 PM
if (post.ContentItem.BlogPostPart.BlogPostImage != null) { // display image }
Jan 27, 2014 at 9:36 PM
Unfortunately, that was the first thing I tried and I still get an error message. I also tried doing post.ContentItem.BlogPostPart.Fields.Count() > 0, but that produced an error as well.

Thanks for the suggestion though.
Jan 27, 2014 at 11:35 PM
I don't know if it is what you are looking for but I use something as this in a mediapicker alternate
@{
    var field = (MediaLibraryPickerField) Model.ContentField;
    string name = field.DisplayName;
    var mediaParts = field.MediaParts;

    var returnUrl = ViewContext.RequestContext.HttpContext.Request.ToUrlString();
}
<span class="name">@name:</span>
<p class="media-library-picker-field media-library-picker-field-@name.HtmlClassify()">
    
    @if (mediaParts.Any()) {   your code  }
Jan 28, 2014 at 6:48 AM
I thought it was too easy :) This might work:
var part = (Orchard.ContentManagement.ContentPart) post.ContentItem.BlogPostPart;
var imageField = part.Fields.Where(field => field.PartFieldDefinition.Name == "BlogPostImage").SingleOrDefault() as MediaLIbraryPickerField;
if (imageField != null) {

}
Marked as answer by psenechal on 1/28/2014 at 11:41 AM
Jan 28, 2014 at 7:41 PM
Thanks Kass...that worked!