Reputation: 116
I have a Controller that has two action methods used by a page:
The standard OnGet, that is called, when the page is visited in browser and another method SortData that is called using an anchor tag.
Both of these methods interact with the same property of the controller, but there seem to be like two different object references to the property for each of the methods, because the data inside SortData is inconsistent with the date in OnGet.
Also, if I won't initialize that property inside the Controller's constructor but inside the OnGet method, it will be null inside SortData, even though OnGet has been called first.
My question is how do I get SortData to use the same Property that OnGet uses?
The code looks like this:
public class MyController : Controller
{
private MyClass Property {get; set;}
public SearchController()
{
Property = new MyClass()
}
[HttpGet("sortdata")]
public IActionResult SortData(string sortAttribute)
{
Property.SortData(sortAttribute);
return View("Index", Property);
}
public IActionResult OnGet([FromQuery]string requeststring)
{
ViewData["Message"] = requeststring;
Property.Datas = requeststring == null ?
searchService.GetAll() :
searchService.searchByRequestString(requeststring);
return View("Index", Property);
}
}
Of course, the service used in OnGet is being initialized in the Controller as well, but I removed it from the example to keep it rather simple.
So you can see that OnGet modifies Property and returns the Index page. At that page, there is an anchor that calls SortData which also modifies Property. But it is not the same Property as in OnGet, it is still at it's state of initialization. But I want the actual Property to be modified and then return the Index page with sorted data.
Upvotes: 1
Views: 75
Reputation: 93444
Yes, this is correct behavior. Each web request lives in it’s own context. you have two web requests, it instantiates a new controller for each request, so of course you do not have the same instance of the property.
Now that you know that this is the correct behavior, you will want ask a new question, which will be how do you share a property across multiple requests. That, however is the wrong question. The answer to that is “you don’t”. web requests should be stateless. instead, you should add your sort parameters to the query parameters.
Upvotes: 6