Either you cheat a bit and put a bit of logic in the view. A better way is to handle that in the controller and store it in a viewmodel. For the alloy demo site that would look like this in the controller for the contact block:
//View model class public class ContactBlockModel { //Either use a new viewmodel class for image (instead of reference) or cheat a little and use the imagefile class directly. public ImageFile Image { get; set; } public string Heading { get; set; } public string LinkText { get; set; } public IHtmlString LinkUrl { get; set; } public bool ShowLink { get; set; } public ContactPage ContactPage { get; set; } } //Controller needs to set the viewmodel and the image file property public override ActionResult Index(ContactBlock currentBlock) { ImageFile image = null; if(currentBlock.Image!=null) { image = _contentLoader.Get<ImageFile>(currentBlock.Image); } var model = new ContactBlockModel { Heading = currentBlock.Heading, Image = image }; //As we're using a separate view model with different property names than the content object //we connect the view models properties with the content objects so that they can be edited. ViewData.GetEditHints<ContactBlockModel, ContactBlock>() .AddConnection(x => x.Heading, x => x.Heading) .AddConnection(x => (object)x.Image, x => (object)x.Image); return PartialView(model); }
Then you need a new view in Views/Shared/DisplayTemplates/ImageFile.cshtml to display the result like:
@model EpiserverSite4.Models.Media.ImageFile @if (Model != null) { <img src="@Url.ContentUrl(Model.ContentLink)" alt="@Model.Description" /> }
Something like that? You can make it a little prettier by using your own viewmodel for the image class or cheat a little like I do above and use the ImageFile class directly. It's a matter of taste.
If you have a multi-language website, you would probably want to have image alt. text in several languages. ImageData and its properties don't have support for several languages. There are some hacks here and there...
So we usually create an image block, upload an image only once, and do localization in blocks.
Something like this:
[ContentType(GUID = "...", AvailableInEditMode = false)] public class ImageBlock : BlockData { [Display( GroupName = SystemTabNames.Content, Order = 100)] [UIHint(UIHint.Image)] [AllowedTypes(typeof(ImageFile))] [DefaultDragAndDropTarget] [CultureSpecific] public virtual ContentReference ImageUrl { get; set; } [Display( GroupName = SystemTabNames.Content, Order = 200)] [CultureSpecific] public virtual string AltText { get; set; } ... }
ImageBlock is then used as a local block/property instead of ContentReference.
I have a Property on a Page type that looks like this:
And this is what my ImageFile class looks like:
In my razor view this is how I render this image:
This works - but how do I get the Description property from the ImageFile class? I want to use this property for the alt tag of the image.
Thanks
Ayo