✅ Returning a view with a custom model / adding fi...
# help-with-umbraco
j
Happy Saturday / God lørdag! Goal: add custom properties to a ModelsBuilder-created model which can be defined and calculated by a controller and then passed into a View (first image). Purpose is to remove logic from View and move to Controller. Following [this](https://docs.umbraco.com/umbraco-cms/v/10.latest-lts/reference/routing/custom-controllers#returning-a-view-with-a-custom-model) part of the docs I was largely successful in defining the ViewModel and Controller which "extended" the Home Model, but when I passed the ViewModel into the View I "lost access" to the original Home Model fields in a strongly-typed manner i.e. no longer intellisensable. The docs seem to say that I'd need to access the original Home Model's fields using syntax such as
Model.Value<IHtmlString>("productDescription"))
rather than
Model.productDescription
(second image) which isn't ideal. Could anyone advise me on this? I've included
HomeViewModel.cs
,
HomeController.cs
and
home.cshtml
for transparency of my current approach. Greatly appreciate any input.
d
Hi there! I have a very simple solution for you: have your HomeViewModel inherit feom ContentModels.Home instead of PublishedContentWrapped
j
@D_Inventor OH that's brilliant. Yep that's what I was looking for, thank you, #h5yr! Two quick related follow-ups at the HomeController side if that's ok? 1) To be able to query the current
Home
fields in the
HomeController
I've been casting the
CurrentPage
as
Home
- is that correct? 2)
CurrentPage
can be nullable - what would be the best way to handle this? I'm assuming it'd be like
if(CurrentPage == null){return ErrorPage]
, I'm just not too sure on how to call an error page as an IActionResult (if that's correct!) Code of
HomeController.cs
Copy code
csharp
        public override IActionResult Index()
        {
            var currentPage = CurrentPage as Home;
            var homeViewModel = new HomeViewModel(CurrentPage,
                new PublishedValueFallback(_serviceContext, _variationContextAccessor))
            {
                HasImage = !currentPage.MainImage.IsObjectNullOrEmptyString()
            };
            
            return CurrentTemplate(homeViewModel);
        }
d
Though technically
CurrentPage
can be null, I don't think it ever is in practice. I usually go with a simple pattern match like this:
Copy code
if (CurrentPage is not Home content) return CurrentTemplate(CurrentPage)

// do the rest
I usually just return the current template, but it's also a good place to throw an
InvalidOperationException
, whichever has your preference.
j
Makes sense - thank you so much!
FYI I've now made a YT video tutorial on this as a reminder to future me:

https://youtu.be/RNesCW0AncM

6 Views