3

I am using asp.net core 2.1.

My Main page in under Pages folder and my partial view which is _test2 is in shared folder. This is my Main page:

public class MainModel : PageModel
    {
        public IRepositoryStudent irep;
        public MainModel (IRepositoryStudent _irep){
         irep = _irep;
        }
        [BindProperty]
        public Student student{ get; set; }

        public void OnGet()
        {
            student = irep.GetFirst();
        }
    }

This is my Main.cshtml:

@page
@model APWeb.Pages.MainModel

<h2>Main</h2>
<partial name="_test2" model="Model.student" />

This is my partial view : _test2:

@page
@*
    For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@

@model Student
@{ 
<h1 >@Model.Name</h1>}

my model in partial view is null and I have this error:

NullReferenceException: Object reference not set to an instance of an object.
APWeb.Pages.Shared.Pages_Shared__test2.get_Model()

Any help will be appreciate.

2 Answers 2

16

I resolved my issue bye removing '@page' from partial view.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. You saved my day! This was exactly what was required. :)
This is such a ridiculous simple solution, which I doubt was mentioned in the docs that I was reading. :facepalm:
1

The partial view need to be a view page rather than razor page. here is a demo worked: Main page:

public class MainModel : PageModel
    {
        [BindProperty]
        public Student1 student { get; set; }
        public void OnGet()
        {
            student = new Student1 { Name = "Moddy" };
        }
    }

Main.cshtml:

@page
@model ModelValidation_MVC_.Pages.MainModel
@{
    ViewData["Title"] = "Main";
}

<h1>Main</h1>
<partial name="_test2" model="Model.student" />

_test2.cshtml:

@model ModelValidation_MVC_.Models.Student1

<h1>@Model.Name</h1>

Student1.class:

public class Student1
    {
        public string Name { get; set; }
    }

result: enter image description here

1 Comment

Your code is same as mine with one difference which was the key: removing @page from partial view.Thanks anyway,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.