I'm working on my first Umbraco 6 MVC website, its just took me about an hour to work out how to display a content managed image in a razor view. It cant be that hard, I must be missing something...
This is what I ended up with...
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = null;
}
<!Doctype HTML>
<html>
<head>
<title>blah</title>
</head>
<body>
<header>
<img src="@Umbraco.TypedMedia(Int32.Parse(Model.Content.GetPropertyValue("siteLogo").ToString())).GetPropertyValue("umbracoFile")"/>
</header>
</body>
</html>
... which seems overly complicated to just display an image? Surely this cant be best practice using razor?
Two things here:
You don't need to cast the property value to an Int32
, as TypeMedia()
accepts a string
or object
id parameter.
You can use the Url
property of the IPublishedContent
instead of GetPropertyValue("umbracoFile")
So it becomes:
<img src="@Umbraco.TypedMedia(Model.Content.GetPropertyValue("siteLogo")).Url"/>
Which is much nicer isn't it? There are obviously many ways to shortne this, extension methods but one that a friend showed me recently was uMapper which allows you to create strongly typed objects corresponding to your document types, working much like AutoMapper. For a little leg work up front, your code can become much more understandable and concise.