Telerik DropDown List not populating correctly
Emily Wong
My razor code icludes this telerik dropdown list:
<TelerikDropDownList Data="@BkAccounts" TextField="@(nameof(BkAccounts.DisplayField))" ValueField="@(nameof(BkAccounts.BIC))" Value=1 ></TelerikDropDownList>It points to this class:
public class BkAccounts
{ public int Id { get; set; } public string Iban { get; set; } public string BIC{ get; set; } public string DisplayField{ get { return this.Iban + " - " + this.BIC; } }
}If I write it this way, the dropdown list does not populate correctly.
If I change it this way:
<TelerikDropDownList Data="@BkAccounts" TextField="@(nameof(BkAccounts.DisplayField))" ValueField="@(nameof(BkAccounts.Id))" Value=1 ></TelerikDropDownList>It works fine.
Actually, I want to remove the Id field from this BkAccounts class but I am not able to have the DDL to populatecorrectly. What did I miss? According to Telerik doc, TextField can accept a string field so it should not be a format problem...
Edit: the difference between the 2 snippets stands here: ValueField="@(nameof(BkAccounts.BIC) ---> does NOT populate ValueField="@(nameof(BkAccounts.Id) ---> populates like a charm
22 Answers
I got the answer from Telerik forum:
I needed to add into my TelerikDropDownList code: @bind-Value=@SelectedBankAccount and declare it as a string property into theviewmodel
I start to strongly suspect that the issue is on Telerik side. Here is their sample TelerikDropDownList code from
@page "/dropdownlist/overview"
@page "/dropdownlist/index"
@using TelerikBlazorDemos.Shared
<div> <div> <div>T-Shirt size:</div> <TelerikDropDownList Data="@Data" @bind-Value=@SelectedSizeMetric PopupHeight="" DefaultText="Select your T-shirt size" ValueField="SizeMetric" TextField="SizeText"> </TelerikDropDownList> </div> <div> Selected Size Number: <strong>@SelectedSizeMetric</strong> </div>
</div>
@code { public IEnumerable<Size> Data { get; set; } public bool AllowCustom { get; set; } = true; public int? SelectedSizeMetric { get; set; } public string SelectedSize { get; set; } public class Size { public string SizeText { get; set; } public int? SizeMetric { get; set; } } protected override void OnInitialized() { List<Size> sizes = new List<Size>(); sizes.Add(new Size() { SizeText = "X-Small", SizeMetric = 3 }); sizes.Add(new Size() { SizeText = "Small", SizeMetric = 6 }); sizes.Add(new Size() { SizeText = "Medium", SizeMetric = 8 }); sizes.Add(new Size() { SizeText = "Large", SizeMetric = 10 }); sizes.Add(new Size() { SizeText = "X-Large", SizeMetric = 12 }); Data = sizes.AsQueryable(); base.OnInitialized(); }
}It works fine as it is. But if I change:
ValueField="SizeMetric" //int typefor:
ValueField="SizeText" //string typeit nolonger works... I get: System.InvalidCastException : 'Unable to cast object of type 'System.String' to type 'System.Nullable`1[System.Int32]'.'
1