Reputation: 3
I am developing a JavaScript calendar based system to display dates for events in .Net Core and the issue I am having is iterating through the foreach loop and the last value is the only value that is displaying on my calendar , controller code as follows:
public IActionResult Calendar()
{
var dateList = _context.Tasks.Select(x => x.DateAllTaskCompleted != null ? x.DateAllTaskCompleted.Value.ToString("yyyy-MM-dd") : null).ToList();
var jsonDate="";
foreach (var item in dateList)
{
if (item != null)
{
// TODO: Display all dates
jsonDate = JsonSerializer.Serialize(item);
}
}
ViewData["Date"] = jsonDate;
return View();
}
What solutions or adjustments can I make ?
Upvotes: 0
Views: 82
Reputation: 1450
Your code does not work because you are overriding jsonDate
in each loop iteration. If you want to retrieve all dates you will need to declare, for example, jsonDates
as list, and then to append to list in each iteration. Something like this:
public IActionResult Calendar()
{
var dateList = _context.Tasks.Select(x => x.DateAllTaskCompleted != null ? x.DateAllTaskCompleted.Value.ToString("yyyy-MM-dd") : null).ToList();
List<string> jsonDates = new List<string>();
foreach (var item in dateList)
{
if (item != null)
{
// TODO: Display all dates
jsonDates.Add(JsonSerializer.Serialize(item));
}
}
ViewData["Date"] = jsonDates;
return View();
}
Upvotes: 2