Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Pam 2 posts 72 karma points
    Jun 11, 2019 @ 22:08
    Pam
    0

    Querying document types in model constructor

    Hello,

    I've been able to successfully query page info from within a partial view, for example:

    var info = Umbraco.TypedContent(2016).Children("foo").Where(x => x.IsVisible());

    Is it possible to access the same information from within the model .cs file? Ideally, whenever a new instance of the model is created, I'd like to execute some code within the constructor that will populate one of the properties with info from a custom document type.

    Or, if I'm thinking about this all wrong, let me know.

    Thanks, Pam


    UPDATE: I found the documentation I was looking for and was able to access most of the functionality with UmbracoHelper:

    var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

    Just had to make sure I added using System.Linq and Umbraco.Web

  • Søren Kottal 702 posts 4497 karma points MVP 5x c-trib
    Jun 12, 2019 @ 08:42
    Søren Kottal
    0

    Hi Pam

    This is bad practise, and explained in the docs:

    The scope and life-cycle of a model is not specified. In other words, you don't know whether the model exists only for you and for the context of the current request, or if it is cached by Umbraco and shared by all requests. Even though as of version 7.4 Umbraco creates distinct models for each request, this will not always be true.

    As a consequence, the following code has a major issue: the TextPage model "caches" an instance of the HomePageDocument model that will never be updated if the home page is re-published.

    public partial class TextPage
    {
      public TextPage(IPublishedContent content)
        : base(content)
      {
        HomePage = content.AncestorOrSelf(1) as HomePageDocument;
      }
    
      public HomePageDocument HomePage { get; private set; }
    }
    

    As a rule of thumb, models should never, ever reference and cache other models.

Please Sign in or register to post replies

Write your reply to:

Draft