Copied to clipboard

Flag this post as spam?

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


  • Paul Griffiths 370 posts 1021 karma points
    Sep 30, 2019 @ 17:44
    Paul Griffiths
    0

    Strongly typing in v8 Custom Controller

    Hi,

    Following the official documentation at https://our.umbraco.com/documentation/reference/routing/custom-controllers I am attempting to build a custom controller which returns a custom view model.

    Here is my view model

    public class HomePageViewModel : ContentModel
    {
        public HomePageViewModel(IPublishedContent content) : base(content)
        {
        }  
    
        public string Heading { get; set; }
    }
    

    and here is my controller

            public override ActionResult Index(ContentModel model)
        {
            var vm = new HomePageViewModel(model.Content)
            {
                Heading = model.Content.Value<string>("heading")
            };
    
            return CurrentTemplate(vm);
        }
    

    This works as expected but i was wondering whether it is possible to make the contentModel into the type of the model generated by models builder so instead of using model.Content.Value

    I know in v7 when looping through children you could cast to the model type but i was wondering if its possible in the scenario ? I attempted to implement by casting using the bottom suggestion in this post https://stackoverflow.com/questions/34324608/umbraco-cast-ipublishedcontent-type-to-custommodel-type

    I have a core project and .web project. I have used the models builder tool to generate the models into my .core project which is where my controller resides.

    Is the model.Content.Value

    TIA

  • Nik 1617 posts 7263 karma points MVP 7x c-trib
    Sep 30, 2019 @ 19:36
    Nik
    2

    Hi Paul,

    Yes it is possible.

    public override ActionResult Index(ContentModel model)
    {
        //This should do the job :-)
        var typedModel = model.Content as Umbraco.Web.PublishedModels.Home;
    
        var vm = new HomePageViewModel(model.Content)
        {
            Heading = model.Content.Value<string>("heading")
        };
    
        return CurrentTemplate(vm);
    }
    

    Thanks

    Nik

  • Paul Griffiths 370 posts 1021 karma points
    Oct 01, 2019 @ 06:35
    Paul Griffiths
    0

    Good morning Nik,

    Thanks for the reply! I was using the same code as you provided last night but was using model instead of .content :|. Tired mind!

    Do you know whether this strongly typed approach is standard practice i.e. would you expect developers to cast this or would you expect to see model.Content.Value

    I prefer the strongly typed approach but i also want to be following best practices.

    Thanks Paul

Please Sign in or register to post replies

Write your reply to:

Draft