If seems that if databind to an ObservableCollection returned from a (synchronous) property, the DropDownList is updating as the ObservableCollection changes.
If I databind to an ObserverableCollection returned from an asynchronous method, I have to run StateHasChanged() to force the DropDownList to refresh its datasource.
Here are some snippets to demonstrate:
public class ApiDataSourceModel{
public int MyValueField { get; set; }
public string MyTextField { get; set; }
}
public class DropDownModel
public string Value { get; set; }
public string Text { get; set; }
}
public async Task<ObservableCollection<DropDownModel>> GetApiDataSource()
{
//Tried returnApiDataSource as List and even here as ObservableCollection to try to get to refresh DropDownList
ObservableCollection<ApiDataSourceModel> returnApiDataSource = await GetMyApiDataSource();
if (returnApiDataSource is not null)
{
return returnApiDataSource.Select(c => new DropDownModel() { Value = MyValueField.ToString(), Text = MyTextField }).ToList().ConvertIEnumerableToObservableCollection();
}
else
return default(ObservableCollection<Models.System.DropDownModel>);
}
//Custom Extension
public static ObservableCollection<T> ConvertIEnumerableToObservableCollection<T>(this IEnumerable<T> iEnumerableCollection)
{
if (iEnumerableCollection is not null)
return new ObservableCollection<T>(iEnumerableCollection);
else
return null;
}
string selectedApiDataSourceValue;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
ObservableCollection<DropDownModel> sourceForDdl = await GetApiDataSource();
//This won't update DDL without StateHasChanged() even though DDL data is an Observable collection that has been updated.
StateHasChanged();
}
}
DropDownList
<TelerikDropDownList @bind-Value="@selectedApiDataSourceValue"
Id="ApiDataSourceField"
Data="@sourceForDdl ">
</TelerikDropDownList>