Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pass objects from one page to another on ASP.Net Core with 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.

Actually 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).

Can anybody knows how to share objects between razor pages? Is this the correct way to achieve it? or Is there another better way?

Thanks in advance

like image 641
gsaldana Avatar asked Oct 16 '17 14:10

gsaldana


People also ask

How do I pass values between asp net pages?

The following options are available only when the source and target pages are in the same ASP.NET Web application. Use session state. Create public properties in the source page and access the property values in the target page. Get control information in the target page from controls in the source page.


2 Answers

You can pass parameters to specified handlers in the page model class, like this:

return RedirectToPage("Orders", "SingleOrder", new {orderId = order.Id}); 

Where the page model class method has this signature:

public void OnGetSingleOrder(int orderId) 

If you are passing an object, you can pass the object directly, but in my experience any child objects are not populated.

like image 128
hillstuk Avatar answered Sep 17 '22 12:09

hillstuk


The key here is that you need to pass an anonymous object whose property names match the routing constraints defined in the Razor Page.

For example, if you define an id (optional) routing constraint in the Razor Page:

@page "{id?}"

To redirect to that view passing a specific id, just do:

return RedirectToPage("PageName", new { id = 3 }); 

If you just one to redirect to the current page (but passing a specific id), just do:

return RedirectToPage(new { id = 3 }); 

If you just pass the number without the anonymous object it won't work.

like image 44
Eduardo Hernández Avatar answered Sep 16 '22 12:09

Eduardo Hernández