0

I'm creating my 1st ASP.Net Core (3.1) Razor Page Application and have a question regarding the passing of a custom object to a Partial View.

When developing ASP.Net MVC applications in the past, I would have used ViewModels to pass custom objects to Razor Views and Partial Views. However, it is my understanding that the PageModel within a .Net Core Razor Pages application acts as a ViewModel, therefore, there should be no need to use a ViewModel class.

I have been applying this throughout my application, however, I now need to send a custom object to a Partial View from my Razor Page. I have ended up using a ViewModel class to do this as I don't know of another way of doing it (passing multiple data items), however, it feels messy and I would like to know how other developers have approached the same.

Is this approach correct (it does work), or is there another more elegant method?

Razor Page PageModel

//Need to pass the object and select lists to Partial View, but unable to do so because
//They are separate items
[BindProperty]
public Person myPerson { get; set; }
public SelectList selectListOne { get; set; }
public SelectList selectListTwo { get; set; }

//Instead have created a custom ViewModel which I will populate and pass to Partial View
[BindProperty]
public viewModel myViewModel { get; set; }

public IActionResult OnGet()
{
    myViewModel= new viewModel 
    {
       vmPerson = new Person 
       {
           Name = '',
           Date = DateTime.Now
       },
       vmselectListOne = new SelectList(Enumerable.Range(0, 1000).ToList()),
       vmselectListTwo = new SelectList(Enumerable.Range(0, 1000).ToList())
    };

    return Page();
}

Razor Page Cshtml

@page "{Id:int}"
@model MyApp.Web.CreateModel

<partial name="_myPartial" model="Model.myViewModel" />

Partial View

@using MyApp.Web.Models
@model viewModel 

//Populate fields of object and drop down lists etc.

Any advice appreciated.

tcode
  • 5,055
  • 19
  • 65
  • 124

0 Answers0