In the below code, I have a <select>
tag where I am binding the value of SelectedDate
.
When I load the timesheet-dashboard page, and select a value, it correctly navigates to the page. Logging the values in the console log inside OnParametersSetAsync
and OnInitializedAsync
I can see the values are correct. In some redacted code, it filters my data appropriately and all the graphs load as expected with data filtered. The URI shows the correct address.
However, the select element shows a blank. And when I click on select, the value with the check mark next to it is FirstOrDefault value.
I dont quite understand what I am missing here that is causing the value to not bind and display correctly when changing the selection.
@page "/timesheet-dashboard"
@page "/timesheet-dashboard/{StartDate}"
@inject IJSRuntime JSRuntime
@using valkyrie.Services.Timesheets
@using valkyrie.Services.Crm;
@inject TimesheetService TimesheetService;
@inject DealService DealService;
@inject TimesheetRecordService TimesheetRecordService;
@inject IHttpContextAccessor HttpContextAccessor
@inject NavigationManager NavigationManager
@rendermode InteractiveServer
<div class="container">
<div class="col-lg-4 mx-auto pb-3">
<select @bind="SelectedDate" @bind:event="onchange" class="form-select form-control-lg">
@foreach (var date in StartOfWeekDates)
{
<option value="@date.ToShortDateString()">@date.ToShortDateString()</option>
}
</select>
</div>
</div>
@code {
[Parameter]
public string StartDate { get; set; }
private DateTime selectedDate;
public DateTime SelectedDate
{
get { return selectedDate; }
set
{
if (selectedDate != value)
{
selectedDate = value;
NavigationManager.NavigateTo($"/timesheet-dashboard/{selectedDate:yyyy-MM-dd}");
}
}
}
private List<DateTime> StartOfWeekDates { get; set; } = new();
protected override async Task OnInitializedAsync()
{
DateTime someStartDate = DateTime.Now.AddDays(-30);
DateTime someEndDate = DateTime.Now;
var records = TimesheetRecordService.GetAllTimesheetRecords();
StartOfWeekDates = records
.Where(rec => rec.Timesheet != null &&
rec.Timesheet.StartOfWeekDate >= someStartDate &&
rec.Timesheet.StartOfWeekDate <= someEndDate)
.Select(rec => rec.Timesheet.StartOfWeekDate.Date)
.Distinct()
.OrderBy(date => date)
.ToList();
selectedDate = !string.IsNullOrEmpty(StartDate) && DateTime.TryParse(StartDate, out DateTime date) ? date : StartOfWeekDates.FirstOrDefault();
}
protected override async Task OnParametersSetAsync()
{
SelectedDate = !string.IsNullOrEmpty(StartDate) && DateTime.TryParse(StartDate, out DateTime date) ? date : StartOfWeekDates.FirstOrDefault();
}
}
Im expecting the Select element to show the currently selected value.