MediaPickerFields still elude me.
I've defined a new Part in Migrations.cs and added a Boolean
column and a MediaPickerField
to the part as follows:
SchemaBuilder.CreateTable("ImageContentPartRecord", table =>
table.ContentPartRecord()
.Column("DisplayImage", DbType.Boolean));
ContentDefinitionManager.AlterPartDefinition("ImageContentPart", builder =>
builder
.Attachable()
.WithField("ImageField", fld =>
fld.OfType("MediaPickerField")
.WithDisplayName("Image")));
Assuming I have ImageContentPart
and ImageContentPartRecord
classes, how can I retrieve the data from my MediaPickerField (url, dimensions, alt text, class, etc) in my Driver and in my Part Templates (Edit / Display)?
i.e. - Parts.ImageContent.cshtml (I want to accomplish something like this):
<div>
<img src="@Model.ImageField.Url" alt="@Model.ImageField.Alt" />
</div>
Any ideas?
Here is the solution:
In my Display Driver method, I make sure to pass my ImageContentPart
(part
) when building the ContentShape
:
return ContentShape("Parts_ImageContent", () =>
shapeHelper.Parts_ImageContent(
Content: part));
Then in my Template View, I leverage the dynamic nature of Orchard's architecture to consume my MediaPickerField
. To do this, you access the .ContentItem
property on your part, then leaning on dynamics, chain the part name (.ImageContentPart
) and then the field name (.ImageContent
) to access the field.
@{
// Attempting to access MediaPickerField named 'ImageContent'
var image = Model.Content.ContentItem.ImageContentPart.ImageContent;
// Leaning on Orchard dynamics to access properties of the field
var url = image.Url;
}
<img src="@url" alt="@T(image.AlternateText)" />
Here is an exhaustive list of MediaPickerField properties from \\Orchard.Fields\Views\Fields\MediaPicker.cshtml
:
@*
Alternate Text: @Model.ContentField.AlternateText
Class: @Model.ContentField.Class
Style: @Model.ContentField.Style
Alignment: @Model.ContentField.Alignment
Width: @Model.ContentField.Width
Height: @Model.ContentField.Height
Url: @Model.ContentField.Url
You can also display an image using this example, and add the attributes you need:
<img src="@Href(Model.ContentField.Url)" />
*@
Hopefully, if you stumble upon a similar problem, this will help out!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With