I start learning asp.net core MVC for practice purposes I created one HomeController
in which I have two methods
[Route("[controller]/[action]")]
public class HomeController : Controller
{
private readonly JobRepository _jobRepository;
public HomeController()
{
_jobRepository = new JobRepository();
}
[HttpPost]
public IActionResult AddJob(int job)
{
return Ok(_jobRepository.AddJob(job));
}
[HttpGet]
public IActionResult GetAllJobs()
{
return Ok(_jobRepository.GetAllJobs());
}
}
I am receiving data in my controller but the problem is when the data is transferred to my repository where I am saving all the Jobs in the int list
public class JobRepository
{
List<int> jobs = new List<int>();
public int AddJob(int job)
{
jobs.Add(job);
return job;
}
public List<int> GetAllJobs()
{
return jobs;
}
}
The data is entered in the list but when I do another hit on my controller my list is reinitialized and the list count shows 1 in the immediate window
2
Answers
Each time you enter JobRepository it creates a new object of the List so it will be empty
If you want to store it temporally then make the object as static to avoid creating a new object each time
If you want persistence you may want to use database and entityframework
Refer for documentation
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-6.0
This ignores your DI registration settings.
Instead do:
or without interface (which I wouldn’t recommend):
unrelated, I’d also recommend to add the null check