asp.net core partialview issue

Strosala Ioan 61 Reputation points
2023-07-22T07:20:58.7+00:00

Hi. I want to include one in the project one partialview, however I do it, it doesn't work.

Here is example:

  • this is the model
public class Student 
   {   

        public int Id { get; set; } 
        public string Name { get; set; } 
  }	
  • this is the controller
 public IActionResult ViewStudent() 
    { 
      Student std = new Student
     {
       Name = "John Doe",
       Id = 1
      };     
 return PartialView("_ViewStudent", std)  }
  • and the view Index contain

<div>
<div class="container py-4">

@await Html.PartialAsync("_ViewStudent.cshtml")

</div>

</div>

  • partial view _ViewStudent
@model Student;
<div>
    <div>
        <div> Student id: @Model.Id</div>
        <div> Student id: @Model.Name</div>
    </div>
</div>

When I run the application returns the following error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get returned null.

Please help me to solve this issue.

Thank you!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,016 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 1,500 Reputation points
    2023-07-22T10:15:22.0366667+00:00

    Try passing the Student model to the partial view.

    https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-7.0

    @await Html.PartialAsync("_ViewStudent.cshtml", partialViewData)