Reputation: 551
I am testing Umbraco and trying to set up a list of blogs on a page. I have a custom BlogMode.cs which looks like this:
public class BlogPostModel : RenderModel
{
public BlogPostModel() : base(UmbracoContext.Current.PublishedContentRequest.PublishedContent)
{
}
public string MainBlogImage { get; set; }
public string ImageAltText { get; set; }
public string Introduction { get; set; }
public string Category { get; set; }
public IEnumerable<IPublishedContent> BlogPosts { get; set; }
}
This works fine as nor my Model will have the properties above. Now what I am trying to do is get all the blog post by using this:
var posts = Model.Content.Children.ToList();
But what this does is creates a list of type IPublishedContent
. So now I can not use Model.Introduction
or Model.ImageAltText
or any other property in my blog model because it is of type IPublishedContent
How would I get this collection and make it of type BlogModel
?
Upvotes: 3
Views: 6784
Reputation: 2316
Fast Forward 2019:
These days I'd use the baked in Umbraco ModelsBuilder. It will generate the strongly typed models for you out of the box, with enough extension points to be able to customise those models as well as where and how they are generated.
For more information, take a look at the ModelsBuilder wiki on GitHub:
https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/Umbraco.ModelsBuilder
Original Answer circa 2015:
My recommendation is to use Ditto - there's a Nuget package available and allows you to write code like this:
var posts = Model.Content.Children.As<BlogPostModel>();
You'll find documentation on Ditto here: https://github.com/leekelleher/umbraco-ditto and there's also lots of information about it in blog posts etc.
Basically, you write yourself a Model and then can map it directly using the Ditto As<Model>()
generic extension method.
Upvotes: 4
Reputation: 196
Not sure what version of Umbraco you're using but i'm using 7.4.3 (which includes the model builder) and this works for me.
var page = umbracoHelper.TypedContent(relatedLink.Internal);
if (page.ContentType.Alias.Equals("editorial"))
{
var typedPage = (Editorial)page;
//Your code here, for example 'typedPage.SiteLinkImage'
}
The 'Editorial' class was generated by the model builder.
Upvotes: 8