Search code examples
c#asp.net-corerazor-pages

How to pass objects from one page to another in ASP.NET Core Razor Pages?


I'm developing a web application using ASP.NET Core 2.0 with Razor Pages. I'm creating an object with some data and want to send that object to another page. I'm doing this:

var customObject = new{
   //some values
};
return RedirectToPage("NewPage", customObject);

I see that the URL has the values of the object I'm sending, but I can't find how to take that values (in the NewPage instance).

How do I share objects between Razor Pages? Is this the correct way to achieve it?


Solution

  • I don't know if that might help you or it is good practice for MVVM flavours like Razor, but inside ASP.NET Core API projects I often use custom global DI'ed services, like

    public void ConfigureServices(IServiceCollection services)
    {
        ...
    
        services.AddSingleton<IMyService, MyService>();
    
        ...
    
         services.AddMvc();
    }
    

    You can exchange data between your IndexModel and a CustomModel eg. by setting it like

    public class CustomModel : PageModel
    {
       public IMyService _myService;
    
       public CustomModel(IMyService myService)
       {
           _myService = myService;
       }
    
       public async Task<IActionResult> OnPostAsync(...)
       {
            ...
    
            _myService.SetDataOrSometing(...);
    
            ...
    
            return RedirectToPage();
       }
    }
    

    and retrieving it like

    public class IndexModel : PageModel
    {
        public IMyService _myService;
    
        public IndexModel(IMyService myService)
        {
            _myService = myService;
        }
    
        public void OnGet()
        {
            var data = _myService.GetDataOrSomething();
        }
    }
    

    From here you can also use an ObserveableCollection and register events to get the updates down to your PageModels.

    IMHO this is a way to pass objects from one page to another with a clean separation of concerns.