How to Use Razor Partial Tag Helper in a Layout

Viewed 544

After reviewing an old Razor application, I decided to update it, unable to get the partial tag helper to work, I upgraded to Visual Studio (Community) 2019 as all the information I could find instructed from there, and made a new ASP.NET Core 5.0 Razor project that actually included a Pages folder.

Now after attempting to use a Layout that uses a partial, I get the following error:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'WebApplication1.Pages.IndexModel', but this ViewDataDictionary instance requires a model item of type 'WebApplication1.Pages.Shared.PartAModel'.

Please tell me what simple thing I missed that makes this work.

There should only be 3-5 files on consequence so I'll example them here:

Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <p>
        This is the parent content.
    </p>
</div>

_Layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<body>
   
    <div>
        @RenderBody()
    </div>

    <div>
        <partial name="PartA" />
    </div>
        
</body>
</html>

PartA.cshtml:

@page
@model WebApplication1.Pages.Shared.PartAModel
@{
}
This is where the child content goes.

Index.cshtml.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }
    }
}

PartA.cshtml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication1.Pages.Shared
{
    public class PartAModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
1 Answers

PartA.cshtml page strongly binds with WebApplication1.Pages.Shared.PartAModel.

You need to pass the same model through partial tag:

@{var part = new PartAModel;}
<div>
   <partial name="PartA"  model="@part" />
</div>

See Also: How to pass a value into partial tag helper?

Related