Umbraco 将 "IPublishedContent" 类型转换为 "CustomModel" 类型
Umbraco Cast "IPublishedContent" type to "CustomModel" type
我正在测试 Umbraco 并尝试在页面上设置博客列表。我有一个自定义 BlogMode.cs,看起来像这样:
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; }
}
这很好用,因为我的模型也不具有上述属性。现在我想做的是通过使用以下命令获取所有博客 post:
var posts = Model.Content.Children.ToList();
但是它所做的是创建一个 IPublishedContent
类型的列表。所以现在我不能在我的博客模型中使用 Model.Introduction
或 Model.ImageAltText
或任何其他 属性 因为它是类型 IPublishedContent
如何获得此集合并将其设为 BlogModel
类型?
快进 2019:
这些天我会使用 Umbraco ModelsBuilder 中的烘焙工具。它将为您生成开箱即用的强类型模型,具有足够的扩展点,能够自定义这些模型以及生成它们的位置和方式。
有关详细信息,请查看 GitHub 上的 ModelsBuilder wiki:
https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/Umbraco.ModelsBuilder
大约 2015 年的原始答案:
我的建议是使用 Ditto - 有一个 Nuget 包可用,允许您编写如下代码:
var posts = Model.Content.Children.As<BlogPostModel>();
您可以在此处找到有关 Ditto 的文档:https://github.com/leekelleher/umbraco-ditto 并且在博客文章等中也有很多关于它的信息。
基本上,您自己编写一个模型,然后可以使用 Ditto As<Model>()
通用扩展方法直接映射它。
不确定您使用的是哪个版本的 Umbraco,但我使用的是 7.4.3(包括模型构建器),这对我有用。
var page = umbracoHelper.TypedContent(relatedLink.Internal);
if (page.ContentType.Alias.Equals("editorial"))
{
var typedPage = (Editorial)page;
//Your code here, for example 'typedPage.SiteLinkImage'
}
'Editorial' class 是由模型生成器生成的。
我正在测试 Umbraco 并尝试在页面上设置博客列表。我有一个自定义 BlogMode.cs,看起来像这样:
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; }
}
这很好用,因为我的模型也不具有上述属性。现在我想做的是通过使用以下命令获取所有博客 post:
var posts = Model.Content.Children.ToList();
但是它所做的是创建一个 IPublishedContent
类型的列表。所以现在我不能在我的博客模型中使用 Model.Introduction
或 Model.ImageAltText
或任何其他 属性 因为它是类型 IPublishedContent
如何获得此集合并将其设为 BlogModel
类型?
快进 2019:
这些天我会使用 Umbraco ModelsBuilder 中的烘焙工具。它将为您生成开箱即用的强类型模型,具有足够的扩展点,能够自定义这些模型以及生成它们的位置和方式。
有关详细信息,请查看 GitHub 上的 ModelsBuilder wiki:
https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/Umbraco.ModelsBuilder
大约 2015 年的原始答案:
我的建议是使用 Ditto - 有一个 Nuget 包可用,允许您编写如下代码:
var posts = Model.Content.Children.As<BlogPostModel>();
您可以在此处找到有关 Ditto 的文档:https://github.com/leekelleher/umbraco-ditto 并且在博客文章等中也有很多关于它的信息。
基本上,您自己编写一个模型,然后可以使用 Ditto As<Model>()
通用扩展方法直接映射它。
不确定您使用的是哪个版本的 Umbraco,但我使用的是 7.4.3(包括模型构建器),这对我有用。
var page = umbracoHelper.TypedContent(relatedLink.Internal);
if (page.ContentType.Alias.Equals("editorial"))
{
var typedPage = (Editorial)page;
//Your code here, for example 'typedPage.SiteLinkImage'
}
'Editorial' class 是由模型生成器生成的。