I need to pass collection with the redirect. But "RedirectToPage" sends only via GET request.
Is it another way, to send data with redirect?
public class ListModel : PageModel
{
List<Entity> CreationResults = new List<Entity>();
if (Results.Any(x => x.Message == "Object was not created."))
{
foreach (var item in Results)
{
CreationResults.Add(item);
}
return RedirectToPage("CreateError", new { errorsList = Results });
}
}
My target page handler:
public class CreateError : PageModel
{
public List<Entity> errorsList { get; set; }
public async Task<IActionResult> OnGetAsync(List<Entity> errorsList)
{
this.errorsList = errorsList;
return Page();
}
}
For RedirectToPage
,it contains the following contributors:
public virtual RedirectToPageResult RedirectToPage(string pageName);
public virtual RedirectToPageResult RedirectToPage();
public virtual RedirectToPageResult RedirectToPage(object routeValues);
public virtual RedirectToPageResult RedirectToPage(string pageName, object routeValues);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues, string fragment);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, string fragment);
The only parameter you could pass data is the routeValues
,but you can't pass complex objects as route data. The route data feature only supports simple objects like int and string. If you want to retain more complex objects across requests, you need to use Sessions
or TempData
.
For TempData
,it uses Session, which itself uses IDistributedCache
. IDistributedCache
doesn't have the capability to accept objects or to serialize objects.
Here is the working demo like below:
Index.cshtml.cs:
public IActionResult OnGet()
{
var model = new List<Entity>()
{
new Entity(){ error="aaa"},
new Entity(){ error="nbb"}
};
//for asp.net core 2.x,you could use NewtonSoft.Json -----JsonConvert.SerializeObject(model);
//this is for asp.net core 3.x by using System.Text.Json
TempData["errorsList"] = JsonSerializer.Serialize(model);
return RedirectToPage("CreateError");
}
CreateError.cshtml.cs:
public class CreateError : PageModel
{
public List<Entity> errorsList { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var data = TempData["errorsList"] as string;
//for asp.net core 2.x ------JsonConvert.DeserializeObject<List<Entity>>(data)
//for asp.net core 3.x
this.errorsList = JsonSerializer.Deserialize<List<Entity>>(data);
return Page();
}
}