How to bind Dictionary<string, string>

Hi,

I want to bind a Dictionary<string, string> but get an error

<SfDropDownList CssClass="e-outline e-success" TValue="string" TItem="KeyValuePair<string, string>"
                                                     DataSource=myDictionary @bind-Value=myProp  [email protected]>
                                        <DropDownListFieldSettings Text="Value" Value="Key"></DropDownListFieldSettings> 
                                    </SfDropDownList>

Error: System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' to type 'System.Collections.Generic.IEnumerable`1[System.Object]'.

What's wrong? What's the correct way to do it?

Regards

7 Replies 1 reply marked as answer

PM Ponmani Murugaiyan Syncfusion Team July 1, 2020 11:29 AM UTC

Hi Jorge,   
  
Greetings from Syncfusion support. 
 
We have checked the reported requirement. The DataSource property of the DropDownList component will support the type of ICollection. The dictionary type will not be supported.  Hence convert the dictionary type to the list and bind the data source. Please refer to the code below,  
 
[Index.razor] 
 
<SfDropDownList TValue="string" TItem="Countries" ShowClearButton="false" Placeholder="e.g. Australia" Value="comboValue" DataSource="@DataSource"> 
    <DropDownListFieldSettings Text="Name" Value="Code"></DropDownListFieldSettings> 
    <DropDownListEvents TValue="string" Created="onCreated"></DropDownListEvents> 
</SfDropDownList> 
 
@code { 
 
    ... 
   public void onCreated() 
    { 
        DataSource = Country.Select(p => new Countries { Name = p.Value, Code = p.Key }).ToList(); 
    } 
 
    Dictionary<string, string> Country = new Dictionary<string, string>() { 
        { "1", "Australia"}, 
        { "2", "Bermuda" } 
    }; 
} 
 
 
Kindly check with the above sample. Please get back us if you need further assistance.  
 
Regards,  
Ponmani M 


Marked as answer

JQ Jorge Quesada July 1, 2020 01:32 PM UTC

Hi Ponmani,

Ok! Thanks for your help.

Regards
Jorge 


PM Ponmani Murugaiyan Syncfusion Team July 2, 2020 04:18 AM UTC

Hi Jorge,  

Thanks for your update. Please get back to us if you need further assistance.  

Regards,  
Ponmani M 



GP Guillermo Perez March 22, 2023 06:41 PM UTC

No, this is wrong... the sample is trying to convert from Dictionary<T,T> to other type of object... he's asking how to working with a dictionary directly... here's my working sample:

                                                            <label for="PB_LOD_Project_Selector" class="h6 fw-bold text-primary form-label mb-0">Project:</label>

                                                            <SfDropDownList TItem="KeyValuePair<string, string>" TValue="string"

                                                                    Enabled="@(string.IsNullOrEmpty(KDM_PB_LOD_Form_Model.ProgramName) == false)"

                                                                    @bind-Value="KDM_PB_LOD_Form_Model.ProjectShortName"

                                                                    DataSource="@New_KDM_PB_LOD_SelectorProjects"

                                                                    ID="PB_LOD_Project_Selector">

                                                                <DropDownListFieldSettings Value="Key" Text="Value"></DropDownListFieldSettings>

                                                                <DropDownListEvents TItem="KeyValuePair<string, string>" TValue="string"

                                                                            OnValueSelect="OnValueSelect_PB_LOD_Project_Handler"></DropDownListEvents>

                                                            </SfDropDownList>


                                                            <ValidationMessage AdditionalAttributes="@(new Dictionary<string, object>{ {"fwb", "1"} })" For="() => KDM_PB_LOD_Form_Model.ProjectShortName"></ValidationMessage>




UD UdhayaKumar Duraisamy Syncfusion Team March 23, 2023 02:45 PM UTC

You can use below code snippet to bind a Dictionary<string, string> object to the SfDropDownList.


@using System.Collections.Generic

@using Microsoft.AspNetCore.Components.Web

@using Syncfusion.Blazor.DropDowns

@using System.Linq

 

<p>Select a color:</p>

 

<SfDropDownList TValue="KeyValuePair<string, string>"

                TItem="KeyValuePair<string, string>"

                DataSource="@myDictionary.ToList()"

                @bind-Value="@selectedColor">

    <DropDownListFieldSettings Text="Value" Value="Key" />

</SfDropDownList>

 

<p>You selected: @selectedColor.Value</p>

 

@code {

    private Dictionary<string, string> myDictionary = new Dictionary<string, string>()

    {

        {"Red", "#FF0000"},

        {"Green", "#008000"},

        {"Blue", "#0000FF"}

    };

 

    private KeyValuePair<string, string> selectedColor;

 

    protected override void OnInitialized()

    {

        selectedColor = myDictionary.First();

    }

}



RM Robert Martin November 27, 2023 10:08 PM UTC

How would you bind a more complex dictionary object?

Let's say Dictionary<Guid, CustomObject> values = new Dictionary<Guid, CustomObject>(); ?

In this case I want to store the selected items Guid in a "SelectedObject" variable and in the dropdown, values should be displayed from a string property called "InternalName" from the CustomObject.

What is the best way to go about this? I'd like to not do any transformations on the Dictionary.



PK Priyanka Karthikeyan Syncfusion Team January 4, 2024 12:32 PM UTC

Hi Robert Martin,

Thank you for your patience. We have prepared a sample based on the shared information. Please find the code snippet and sample attached for your reference.

@using System;
@using System.Collections.Generic;
@using Microsoft.AspNetCore.Components.Web;
@using Syncfusion.Blazor.DropDowns;

<p>Select an object:</p>

<SfDropDownList TValue="Guid" TItem="CustomObjectDisplay"
                DataSource="@displayItems"
                @bind-Value="@selectedGuid">

    <DropDownListFieldSettings Text="InternalName" Value="Id" />

</SfDropDownList>

<p>You selected: @selectedGuid</p>

@code {

    private Dictionary<Guid, CustomObject> myDictionary = new Dictionary<Guid, CustomObject>()
    {
        { Guid.NewGuid(), new CustomObject { InternalName = "Object 1" } },
        { Guid.NewGuid(), new CustomObject { InternalName = "Object 2" } },
        { Guid.NewGuid(), new CustomObject { InternalName = "Object 3" } }
    };

    private List<CustomObjectDisplay> displayItems;
    private Guid selectedGuid;

    protected override void OnInitialized()
    {
        displayItems = myDictionary.Select(kv => new CustomObjectDisplay { Id = kv.Key, InternalName = kv.Value.InternalName }).ToList();
        selectedGuid = displayItems.First().Id;
    }

    public class CustomObject
    {
        public string InternalName { get; set; }
        // Add other properties of CustomObject as needed
    }

    public class CustomObjectDisplay
    {
        public Guid Id { get; set; }
        public string InternalName { get; set; }
    }
}


Sample: https://blazorplayground.syncfusion.com/rXrzZMDTJIMrWIES

Regards,

Priyanka K


Loader.
Up arrow icon