Reputation: 51
I would like to pass a complex object (a report) from my Index page to an Edit page. I have custom logic to determine which reports a user has access to that would not be captured with Azure Active Directory/roles. Because of this, I cannot simply pass the id as a route parameter and retrieve it on the Edit page.
Currently I have a list of reports on Index.cs that are displayed in the view with an edit button.
public IEnumerable<Report> Reports { get; set; }
When clicking edit I would like to send that report directly to the Edit page.
public async Task<IActionResult> OnPostEditAsync(long id)
{
var report = Reports.FirstOrDefault(x => x.Id == id);
return RedirectToPage("./Edit", report);
}
However, RedirectToPage
only takes route data. Is there a different method I should be using here to pass this? If the only way to do so is not best practice then feel free to say so as I would not want to implement this if the pattern is bad.
Upvotes: 1
Views: 1286
Reputation: 18159
You can try to use TempData
,here is a demo:
Page1.cshtml:
<form method="post">
<input name="id" />
<input type="submit" value="submit" asp-page-handler="Edit"/>
</form>
Page1.cshtml.cs(I use fake data to test):
public IEnumerable<Report> Reports { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostEditAsync(long id)
{
Reports = new List<Report> { new Report { Id = 1, Name = "Report1" }, new Report { Id = 2, Name = "Report2" }, new Report { Id = 3, Name = "Report3" } };
var report = Reports.FirstOrDefault(x => x.Id == id);
TempData["report"] = JsonConvert.SerializeObject(report);
return RedirectToPage("./Edit");
}
Report(I use a simple model to test):
public class Report
{
public int Id { get; set; }
public string Name { get; set; }
}
Edit.cshtml.cs:
public void OnGet()
{
Report r =JsonConvert.DeserializeObject<Report>(TempData["report"].ToString());
}
Upvotes: 2