Search code examples
c#asp.net-corerazorasp.net-2.0asp.net5

Upgraded from Dotnet Core 2.2 to Dotnet 5. Partials no longer get View Data


Original Problem

I'm working on updating a webapp from dotnet core 2.2 to dotnet 5. Most things are working pretty well, but I'm stuck on the partial views.

The website uses a ton of Ajax requests and most return a small partial view with some html. All the variable information in partial was set through the viewdata.

After updating to dotnet 5 the viewdata comes into the partial as empty.

For example, I'm returning a partial "_mailbox". In the controller you can see that I have stuff in the viewdata:

enter image description here

but when I step into the partial you can see it is blank! In 2.2 it was passed through.

enter image description here

The basic fuction -

public ActionResult OnGetGetMailbox(int id)
{
  ViewData["Fullname"] = "Christopher"
  return Partial("_mailbox")
}

Do you have any ideas what may have gone wrong? I've basically just followed the steps outlined by Microsoft.

How to Reproduce

So I started a brand new project to test and have the same issue -

enter image description here enter image description here

Add a new html partial _test.cshtml

enter image description here

Add a new function in index.cshtml.cs

enter image description here

Then when running the webapp https://localhost:44332/?Handler=test

I should see my name- enter image description here

But it is blank. When debugging and stepping through I see the viewdata is not passed to the view.

Other information

  • It works in Dotnet Core 2.2.105.

  • per the docs the same syntax as 2.2 should work in 5.1. However, as @Brando Zhang pointed out, you have to use the antiquated syntax from dotnet 2.1 to make this work.

  • If you read the docs for the Partial function for dotnet 5 it claims to be part of the Microsoft.AspNetCore.Mvc.RazorPages namespace, but if you try to use that namespace you will find the Partial does not exist. see docs

enter image description here

Is it a bug?


Solution

  • As far as I know, the return Partial is MVC function result not razor pages, if you want to use razor page's Partial result, you should build by yourself.

    More details, you could refer to below codes:

        public IActionResult OnGetTest()
        {
    
            ViewData["Test"] = "test";
            var partialView = "_test";
    
    
            var partialViewResult = new PartialViewResult()
            {
                ViewName = partialView,
                ViewData = ViewData
            };
            return partialViewResult;
        }   
    

    Result:

    enter image description here