'Asp.net Core Razor persist data in a view over reload
In my Razor app I can add in the details below and return the Result in a list, as well as area and cost. How do I persist that list of Results so it saves multiple results?
I am posting the results as
<form method="post">
and using the carpet class as
[BindProperty(SupportsGet = true)]
public Carpet? carpet { get; set; }
My OnPostAsync is
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
some code....
carpet.FinalCost = carpetOperations.TotalInstallCost(carpet);
carpet.Results.Add("Room area " + carpet.RoomArea + "sqm $" + carpet.FinalCost);
}
return Page();
}
But I want to persist the data in my carpet.Results List across different entries.
I have also tried it as a Property
public List<string> CarpetResults { get; set; }
and instantiated it in the constructor
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
CarpetResults = new List<string>();
}
But it still resets after every page load.
Solution 1:[1]
For anyone wondering the same I found a solution without using a db. I am making a small app that is not public facing and only as a teaching tool, so security is not so much an issue, and I didn't want a db.
So I created a static class, and just used that.
public static class StaticList
{
public static List<string>? StaticStudentResults { get; set; } = new
List<string>();
}
And in my codebehind I just passed the data to the same list structure held on the page
StudentResults.AddRange(StaticList.StaticStudentResults);
Naturally this could be a huge security hole and do not recommend it for public facing sites.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | netchicken |

