I'm trying to insert training log into a list that is being used instead of a database, but somewhere in the application it gets lost and the list keeps only the record that was entered via code in the constructor of the TrainingRepository class . At first I thought it was because of the controller that is always being called and so my list would be cleaned.
Repository
public class TrainingRepository : ITrainingRepository
{
private List<Treinamento> allTrainings;
private List<Treinamento> trainingData = new List<Treinamento>(); // Repositório
public TrainingRepository()
{
allTrainings = new List<Treinamento>();
trainingData.Add(new Treinamento() { ID = 1, Name = "João da Silva", Duration = "45min", StartDate = DateTime.Parse("10/10/2015"), EndDate = DateTime.Parse("31/10/2015"), Instructor = "Paula", Time = "4:00PM" });
allTrainings.AddRange(trainingData.ToList<Treinamento>());
}
public IEnumerable<Treinamento> GetTrainings()
{
return allTrainings;
}
public Treinamento GetTrainingByID(int id)
{
return allTrainings.Find(t => t.ID == id);
}
public void InsertTraining(Treinamento training)
{
training.ID = (from b in trainingData orderby b.ID descending select b.ID).FirstOrDefault() + 1;
trainingData.Add(new Treinamento()
{
ID = training.ID,
Name = training.Name,
Instructor = training.Instructor,
StartDate = training.StartDate,
EndDate = training.EndDate,
Time = training.Time,
Duration = training.Duration
});
}
public List<string> GetInstructor()
{
var mainItems = (from key in trainingData select key.Instructor).Distinct().ToList();
return mainItems.ToList();
}
}
Controller
public class HomeController : Controller
{
TrainingRepository _trainingRepository = new TrainingRepository();
public ActionResult Index()
{
List<Treinamento> allTrainings = _trainingRepository.GetTrainings().ToList();
return View(allTrainings);
}
[HttpGet]
public ActionResult CreatePartialView()
{
return PartialView("CreatePartialView");
}
[HttpPost]
public void Create(Treinamento training)
{
_trainingRepository.InsertTraining(training);
}
[HttpGet]
public JsonResult GetInstructorList()
{
var allInstructors = _trainingRepository.GetInstructor().ToList();
return Json(allInstructors, JsonRequestBehavior.AllowGet);
}
}