Search code examples
razorumbracoumbraco7

Model to Partial in Umbraco


I have the following snippet on my About Us page (shortened for clarity):

@foreach(var employee in CurrentPage.Employee) {

                  <img class="img-fluid" src="@Umbraco.Media(Convert.ToString(employee.Photo)).umbracoFile" alt="" />


                <h2>@employee.Name</h2>
                <h3>@employee.Title</h3>
                <span>@employee.Bio</span>
        }

The body of the foreach is actually bigger, I specificaly chose to leave the image in the snippet to show the usage of @Umbraco.Media

So I want to extract it to a Partial. Here is the Code of the Partial:

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ContentModels.Employee>
@using ContentModels = Umbraco.Web.PublishedContentModels;
@using Umbraco.Web;

<img class="img-fluid" src="@Umbraco.Media(Convert.ToString(Model.Content.Photo)).umbracoFile" alt="" />

    <h2>@Model.Content.Name</h2>
    <h3>@Model.Content.Title</h3>
    @Model.Content.Bio

The page then becomes this:

@foreach(var employee in CurrentPage.Employee) {

   @Html.Partial("Employee", new global::Umbraco.Web.Models.RenderModel(employee, Model.CurrentCulture))
        }

Problem is that I'm getting

 Cannot bind source content type Umbraco.Web.Models.DynamicPublishedContent to model content type Umbraco.Web.PublishedContentModels.Employee.

I think my problem comes from the fact that I loop through my Employees with CurrentPage.Employee rather than going through something like Model.Children.

Anyway, is there a way to get the Model out of the DynamicPublishedContent ?


Solution

  • I found out what my problem was. Actually and as a rule of thumb, you should not use CurrentPage

    I changed the code in the About Us page to this:

     @foreach(var employee in Model.Content.Children("Employee")) {
         @Html.Partial("Employee", employee)
     }
    

    Then my partial view needs to start like this:

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ContentModels.Employee>
    @using ContentModels = Umbraco.Web.PublishedContentModels;
    

    And then I can use @Model.Name or any other DocumentType property on the Employee.

    That's it!