Home > Back-end >  Show multiple Models in same Razor page: OnGet not firing
Show multiple Models in same Razor page: OnGet not firing

Time:03-16

On a page in my Razor .Net 6 application I have to show the data of 3 models. So I created a Model EigObjFact, comprising the three needed models:

namespace StallingRazor.Model
{
    public class EigObjFact
    {
        public Eigenaar Eigenaren { get; set; }
        public IEnumerable<Model.Object> Objecten { get; set; }
        public IEnumerable<Factuur> Facturen { get; set; }
    }
}

In the Details Page Controller I call the EigObjFact in OnGet:

namespace StallingRazor.Pages.Eigenaren
{
    public class DetailsModel : PageModel
    {
        private readonly ApplicationDbContext _db;
        public DetailsModel(ApplicationDbContext db)
        {
            _db = db;
        }
    
        public async void OnGetAsync(int id)
        {            
            EigObjFact model = new EigObjFact();
            model.Eigenaren = _db.Eigenarens.Find(id);
            model.Objecten = await _db.Objectens.Where(s => s.EigenarenID == id).ToListAsync();
            model.Facturen = await _db.Facturens.Where(x => x.EigenarenID == id).ToListAsync();
            
        }
    }

}

The mapping of the 3 models works fine in the Page because I use:

@model StallingRazor.Model.EigObjFact

Problem: the OnGetAsync handler in the Details page never fires, so the model is empty when used in the page.

What am I missing?

CodePudding user response:

The model of razor page needs to be a PageModel type.So you need to replace @model StallingRazor.Model.EigObjFact with @model StallingRazor.Pages.Eigenaren.DetailsModel.

And you need to add a property which type is EigObjFact to DetailsModel,so that you can get EigObjFact model from DetailsModel:

namespace StallingRazor.Pages.Eigenaren
{
    public class DetailsModel : PageModel
    {
        [BindProperty]
        public EigObjFact model  { get; set; }= new EigObjFact();
        private readonly ApplicationDbContext _db;
        public DetailsModel(ApplicationDbContext db)
        {
            _db = db;
        }
    
        public async void OnGetAsync(int id)
        {            
            model.Eigenaren = _db.Eigenarens.Find(id);
            model.Objecten = await _db.Objectens.Where(s => s.EigenarenID == id).ToListAsync();
            model.Facturen = await _db.Facturens.Where(x => x.EigenarenID == id).ToListAsync();
            
        }
    }

}

Then if you want to use the data of EigObjFact model in view.you can try to use @Model.model.xxx.

  • Related