'ASP.Net Core data POST to method but null in other (metrics with infinite scroll)
I encounter an issue when implementing infinite scroll with ASP.Net Core.
Basically, I initally POST the browser metrics (width, height, etc.) to the controller and store in a private field member _vm.Metrics. I would like some customisations based on the browser window size.
Then, I request the content via the JS fetch API to populate the table rows.
The issue is that _vm.Metrics is null in the GetContent() method. I try to perform a (shallow) copy of the metrics, but it doesn't seem to help. Unless, I miss something, everything in _vm should be the same anywhere in the controller, right?
I understand that HTTP is non-persistent (or stateless) protocol, but I don't understand why it doesn't keep the data inside the controller...
public class FieldsController : Controller
{
private readonly FieldsViewModel _vm;
[HttpPost]
public void Update([FromBody] MetricsModel metrics)
{
_vm.Metrics = metrics;
// _vm.Metrics = metrics.Clone() as MetricsModel;
}
[HttpPost]
public ActionResult GetContent([FromBody] ScrollModel? scroll = null)
{
var metrics = _vm.Metrics; // Always null here…
Return Json();
}
}
Thanks for any help!
Solution 1:[1]
Each http request creates a new instance of your controller, so if you set a field value in a request, the lifespan of that value in the field will be the same as the request, and the next request will not be available The easiest way is to make your field static
private static FieldsViewModel _vm;
But this is not thread safe !! In this case, the best way is to use a session
using System.Text.Json;
[HttpPost]
public void Update([FromBody] MetricsModel metrics)
{
HttpContext.Session.SetString("YOUR_SESSION_KEY", JsonSerializer.Serialize(metrics));
}
[HttpPost]
public ActionResult GetContent([FromBody] ScrollModel? scroll = null)
{
var metricsAsString = HttpContext.Session.GetString("YOUR_SESSION_KEY");
var metrics = JsonSerializer.Deserialize<MetricsModel>(metricsAsString);
Return Json();
}
You must configure the session before using it : configure session in asp.net core
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 |
