Data Binding in Blazor ComboBox Component

22 May 202424 minutes to read

The ComboBox loads the data either from the local data sources or remote data services. Using the DataSource property, bind the local data or using the DataManager, bind the remote data.

  • TItem - Specifies the type of the datasource of the combobox component.

Binding local data

The ComboBox loads the data from local data sources through the DataSource property. It supports the data type of Array of primitive type, Array of object, List of primitive type,List of object, Observable Collection, ExpandoObject, DynamicObject.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    
    <p>ComboBox value is:<strong>@ComboBoxVal</strong></p>
    
    <SfComboBox TValue="string" Placeholder="e.g. Australia" TItem="Country" Width="300px" @bind-Value="@ComboBoxVal" DataSource="@Countries">
        <ComboBoxFieldSettings Text="Name" Value="Code"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
    
        public string ComboBoxVal = "Canada";
    
        public class Country
        {
            public string Name { get; set; }
    
            public string Code { get; set; }
        }
    
        List<Country> Countries = new List<Country>
        {
            new Country() { Name = "Australia", Code = "AU" },
            new Country() { Name = "Bermuda", Code = "BM" },
            new Country() { Name = "Canada", Code = "CA" },
            new Country() { Name = "Cameroon", Code = "CM" },
        };
    }

    Blazor ComboBox with local data binding

    Index value binding

    Index value binding can be achieved by using bind-Index attribute and it supports int and int nullable types. By using this attribute you can bind the values respective to its index.

    @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" Placeholder="e.g. Australia" TItem="Country" @bind-Index="@ddlIndex" DataSource="@Countries">
        <ComboBoxFieldSettings Value="Name"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
    
        private int? ddlIndex { get; set; } = 1;
    
        public class Country
        {
            public string Name { get; set; }
    
            public string Code { get; set; }
        }
    
        List<Country> Countries = new List<Country>
    {
            new Country() { Name = "Australia", Code = "AU" },
            new Country() { Name = "Bermuda", Code = "BM" },
            new Country() { Name = "Canada", Code = "CA" },
            new Country() { Name = "Cameroon", Code = "CM" },
        };
    }

    DataBound event

    The DataBound event triggers when the data source is populated in the popup list.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TItem="GameFields" TValue="string" DataSource="@Games">
        <ComboBoxEvents TItem="GameFields" TValue="string" DataBound="@DataBoundHandler"></ComboBoxEvents>
        <ComboBoxFieldSettings Text="Text" Value="ID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public class GameFields
        {
            public string ID { get; set; }
            public string Text { get; set; }
        }
    
        private List<GameFields> Games = new List<GameFields>() {
            new GameFields(){ ID= "Game1", Text= "American Football" },
            new GameFields(){ ID= "Game2", Text= "Badminton" },
            new GameFields(){ ID= "Game3", Text= "Basketball" },
            new GameFields(){ ID= "Game4", Text= "Cricket" },
         };
    
        private void DataBoundHandler(DataBoundEventArgs args)
        {
            // Here, you can customize your code.
        }
    }

    Primitive type

    Bind the data to the ComboBox as an array or list of the string, int, double and bool type items.

    The following code demonstrates array of string values to the ComboBox component.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="string" Placeholder="Select a game" DataSource="@data" @bind-Value="MyItem" Width="300px"></SfComboBox>
    
    @code {
        List<string> data = new List<string>() { "One", "Two", "Three" };
        public string MyItem { get; set; } = "Two";
    }

    Blazor ComboBox with Primitive string type

    The following code demonstrates array of integer values to the ComboBox component.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="int?" TItem="int?" Placeholder="Select a game" DataSource="@data" @bind-Value="MyItem" Width="300px"></SfComboBox>
    
    @code {
        List<int?> data = new List<int?>() { 100, 200, 300 };
        public int? MyItem { get; set; } = 300;
    }

    Blazor ComboBox with Primitive int type

    Complex data type

    The ComboBox can generate its list items through an array of complex data. For this, the appropriate columns should be mapped to the Fields property.

    In the following example, the Code.ID column and Country.CountryID column from complex data have been mapped to the ComboBoxFieldSettings.Value and ComboBoxFieldSettings.Text respectively.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="Complex" Placeholder="e.g. Select a country" DataSource="@LocalData" @bind-Value="@CountryValue" Width="300px">
        <ComboBoxFieldSettings Text="Country.CountryID" Value="Code.ID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public string CountryValue { get; set; } = "CM";
        public IEnumerable<Complex> LocalData { get; set; } = new Complex().GetData();
    
        public class Code
        {
            public string ID { get; set; }
        }
    
        public class Country
        {
            public string CountryID { get; set; }
        }
    
        public class Complex
        {
            public Country Country { get; set; }
            public Code Code { get; set; }
            public List<Complex> GetData()
            {
                List<Complex> Data = new List<Complex>();
                Data.Add(new Complex() { Country = new Country() { CountryID = "Australia" }, Code = new Code() { ID = "AU" } });
                Data.Add(new Complex() { Country = new Country() { CountryID = "Bermuda" }, Code = new Code() { ID = "BM" } });
                Data.Add(new Complex() { Country = new Country() { CountryID = "Canada" }, Code = new Code() { ID = "CA" } });
                Data.Add(new Complex() { Country = new Country() { CountryID = "Cameroon" }, Code = new Code() { ID = "CM" } });
                Data.Add(new Complex() { Country = new Country() { CountryID = "Denmark" }, Code = new Code() { ID = "DK" } });
                Data.Add(new Complex() { Country = new Country() { CountryID = "France" }, Code = new Code() { ID = "FR" } });
                return Data;
            }
        }
    }

    Blazor ComboBox with Complex data type

    Expando object binding

    Bind the ExpandoObject data to the ComboBox component. In the following example, the ExpandoObject is bound to the collection of vehicles data.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using System.Dynamic
    
    <SfComboBox TItem="ExpandoObject" TValue="string" PopupHeight="230px" Placeholder="Select a vehicle" DataSource="@VehicleData" @bind-Value="@VehicleValue" Width="300px">
        <ComboBoxFieldSettings Text="Text" Value="ID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public string VehicleValue { get; set; } = "1011";
        public List<ExpandoObject> VehicleData { get; set; } = new List<ExpandoObject>();
        protected override void OnInitialized()
        {
            VehicleData = Enumerable.Range(1, 15).Select((x) =>
            {
                dynamic d = new ExpandoObject();
                d.ID = (1000 + x).ToString();
                d.Text = (new string[] { "Hennessey Venom", "Bugatti Chiron", "Bugatti Veyron Super Sport", "SSC Ultimate Aero", "Koenigsegg CCR", "McLaren F1", "Aston Martin One- 77", "Jaguar XJ220", "McLaren P1", "Ferrari LaFerrari", "Mahindra Jaguar", "Hyundai Toyota", "Jeep Volkswagen", "Tata Maruti Suzuki", "Audi Mercedes Benz" }[x - 1]);
                return d;
            }).Cast<ExpandoObject>().ToList<ExpandoObject>();
        }
    }

    Blazor ComboBox with Expando object binding

    Observable collection binding

    Bind the ObservableCollection data to the ComboBox component. In the following example, the Observable Data is bound to a collection of colors data.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using System.Collections.ObjectModel;
    
    <SfComboBox TValue="string" TItem="Colors" PopupHeight="230px" Placeholder="Select a color" DataSource="@ColorsData" @bind-Value="@ColorValue">
        <ComboBoxFieldSettings Text="Color" Value="Code"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public string ColorValue { get; set; } = "#75523C";
        public class Colors
        {
            public string Code { get; set; }
            public string Color { get; set; }
        }
        private ObservableCollection<Colors> ColorsData = new ObservableCollection<Colors>()
        {
            new Colors() { Color = "Chocolate", Code = "#75523C" },
            new Colors() { Color = "CadetBlue", Code = "#3B8289" },
            new Colors() { Color = "DarkOrange", Code = "#FF843D" },
            new Colors() { Color = "DarkRed", Code = "#CA3832"},
            new Colors() { Color = "Fuchsia", Code = "#D44FA3" },
            new Colors() { Color = "HotPink", Code = "#F23F82" },
            new Colors() { Color = "Indigo", Code = "#2F5D81" },
            new Colors() { Color = "LimeGreen", Code = "#4CD242" },
            new Colors() { Color = "OrangeRed", Code = "#FE2A00" },
            new Colors() { Color = "Tomato", Code = "#FF745C" },
            new Colors() { Color = "Brown", Code = "#A52A2A" },
            new Colors() { Color = "Maroon", Code = "#800000" },
            new Colors() { Color = "Green", Code = "#008000" },
            new Colors() { Color = "Pink", Code = "#FFC0CB" },
            new Colors() { Color = "Purple", Code = "#800080" }
        };
    }

    Blazor ComboBox with Observable collection binding

    Dynamic object binding

    Bind the DynamicObject data to the ComboBox component. In the following example, the DynamicObject is bound to the collection of customer data.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using System.Dynamic
    
    <SfComboBox TValue="string" TItem="DynamicDictionary" Placeholder="Select a name" DataSource="@Orders" @bind-Value="@NameValue" Width="300px">
        <ComboBoxFieldSettings Text="CustomerName" Value="CustomerName"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public string NameValue { get; set; } = "Margaret";
        public List<DynamicDictionary> Orders = new List<DynamicDictionary>() { };
        protected override void OnInitialized()
        {
            Orders = Enumerable.Range(1, 15).Select((x) =>
            {
                dynamic d = new DynamicDictionary();
                d.OrderID = 1000 + x;
                d.CustomerName = (new string[] { "Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Anne", "Nige", "Fuller", "Dodsworth", "Leverling", "Callahan", "Suyama", "Davolio" }[x - 1]);
                return d;
            }).Cast<DynamicDictionary>().ToList<DynamicDictionary>();
        }
        public class DynamicDictionary : System.Dynamic.DynamicObject
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                string name = binder.Name;
                return dictionary.TryGetValue(name, out result);
            }
            public override bool TrySetMember(SetMemberBinder binder, object value)
            {
                dictionary[binder.Name] = value;
                return true;
            }
            //The GetDynamicMemberNames method of DynamicObject class must be overridden and return the property names to perform data operation and editing while using DynamicObject.
            public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames()
            {
                return this.dictionary?.Keys;
            }
        }
    }

    Blazor ComboBox with Dynamic object binding

    Enum data binding

    Bind the enum data to the ComboBox component. The following code helps you to get a description value from the enumeration data.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns;
    
    <SfComboBox TValue="Values" TItem="string" Placeholder="e.g. Australia" DataSource="@EnumValues" @bind-Value="@ddlVal" Width="300px">
    </SfComboBox>
    
    @code {
    
        public string[] EnumValues = Enum.GetNames(typeof(Values));
        public Values ddlVal { get; set; } = Values.Canada;
    
        public enum Values
        {
            Australia,
            Bermuda,
            Canada,
            Denmark,
            India,
            US
    
        }
    }

    Blazor ComboBox with Enum data binding

    ValueTuple data binding

    Bind the ValueTuple data to the ComboBox component. The following code helps you to get a string value from the enumeration data by using ValueTuple

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns;
    
    <SfComboBox TItem="(DayOfWeek, string)" Width="250px" TValue="DayOfWeek"
                    DataSource="@(Enum.GetValues<DayOfWeek>().Select(e => (e, e.ToString())))">
        <ComboBoxFieldSettings Value="Item1" Text="Item2" />
    </SfComboBox>

    Blazor ComboBox with ValueTuple data binding

    Binding remote data

    The ComboBox loads the data from remote data services through the DataSource property.

    The ComboBox supports the retrieval of data from the remote data services with the help of the DataManager control. The Query property is used to fetch data from the database and bind it to the ComboBox.

    • DataManager.Url - Defines the service endpoint to fetch data.
    • DataManager.Adaptor - Defines the adaptor option. By default, the ODataAdaptor is used for remote binding. The adaptor is responsible for processing responses and requests from or to the service endpoint.
    • Syncfusion.Blazor.Data package provides some predefined adaptors that are designed to interact with particular service endpoints.

    OnActionBegin event

    The OnActionBegin event triggers before fetching data from the remote server.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using Syncfusion.Blazor.Data
    
    <SfComboBox TValue="string" TItem="OrderDetails" Query="@RemoteDataQuery">
        <SfDataManager Url="https://blazor.syncfusion.com/services/production/api/Orders" CrossDomain="true" Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor"></SfDataManager>
        <ComboBoxEvents TValue="string" TItem="OrderDetails" OnActionBegin="@OnActionBeginhandler"></ComboBoxEvents>
        <ComboBoxFieldSettings Text="CustomerID" Value="CustomerID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public Query RemoteDataQuery = new Query().Select(new List<string> { "CustomerID" }).Take(6).RequiresCount();
        public class OrderDetails
        {
            public int? OrderID { get; set; }
            public string CustomerID { get; set; }
            public int? EmployeeID { get; set; }
            public double? Freight { get; set; }
            public string ShipCity { get; set; }
            public bool Verified { get; set; }
            public DateTime? OrderDate { get; set; }
            public string ShipName { get; set; }
            public string ShipCountry { get; set; }
            public DateTime? ShippedDate { get; set; }
            public string ShipAddress { get; set; }
        }
    
        private void OnActionBeginhandler(ActionBeginEventArgs args)
        {
            // Here, you can customize your code.
        }
    }

    OnActionComplete event

    The OnActionComplete event triggers after data is fetched successfully from the remote server.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using Syncfusion.Blazor.Data
    
    <SfComboBox TValue="string" TItem="OrderDetails" Query="@RemoteDataQuery">
        <SfDataManager Url="https://blazor.syncfusion.com/services/production/api/Orders" CrossDomain="true" Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor"></SfDataManager>
        <ComboBoxEvents TValue="string" TItem="OrderDetails" OnActionComplete="@OnActionCompletehandler"></ComboBoxEvents>
        <ComboBoxFieldSettings Text="CustomerID" Value="CustomerID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public Query RemoteDataQuery = new Query().Select(new List<string> { "CustomerID" }).Take(6).RequiresCount();
        public class OrderDetails
        {
            public int? OrderID { get; set; }
            public string CustomerID { get; set; }
            public int? EmployeeID { get; set; }
            public double? Freight { get; set; }
            public string ShipCity { get; set; }
            public bool Verified { get; set; }
            public DateTime? OrderDate { get; set; }
            public string ShipName { get; set; }
            public string ShipCountry { get; set; }
            public DateTime? ShippedDate { get; set; }
            public string ShipAddress { get; set; }
        }
    
        private void OnActionCompletehandler(ActionCompleteEventArgs<OrderDetails> args)
        {
            // Here, you can customize your code.
        }
    }

    OnActionFailure event

    The OnActionFailure event triggers when the data fetch request from the remote server fails.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using Syncfusion.Blazor.Data
    
    <SfComboBox TValue="string" TItem="OrderDetails" Query="@RemoteDataQuery">
        <SfDataManager Url="https://blazor.syncfusion.com/services/production/api/Orders" CrossDomain="true" Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor"></SfDataManager>
        <ComboBoxEvents TValue="string" TItem="OrderDetails" OnActionFailure="@OnActionFailurehandler"></ComboBoxEvents>
        <ComboBoxFieldSettings Text="CustomerID" Value="CustomerID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public Query RemoteDataQuery = new Query().Select(new List<string> { "CustomerID" }).Take(6).RequiresCount();
        public class OrderDetails
        {
            public int? OrderID { get; set; }
            public string CustomerID { get; set; }
            public int? EmployeeID { get; set; }
            public double? Freight { get; set; }
            public string ShipCity { get; set; }
            public bool Verified { get; set; }
            public DateTime? OrderDate { get; set; }
            public string ShipName { get; set; }
            public string ShipCountry { get; set; }
            public DateTime? ShippedDate { get; set; }
            public string ShipAddress { get; set; }
        }
    
        private void OnActionFailurehandler(Exception args)
        {
            // Here, you can customize your code.
        }
    }

    OData v4 services

    The OData v4 Adaptor provides the ability to consume and manipulate data from OData v4 services. The following sample displays the first six customer details from Customers table of the Northwind Data Service.

  • CSHTML
  • @using Syncfusion.Blazor.Data
    @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="OrderDetails" Placeholder="Select a customer" Query="@Query" @bind-Value="@OrderValue" Width="300px">
        <SfDataManager Url="https://services.odata.org/V4/Northwind/Northwind.svc/Orders" Adaptor="Syncfusion.Blazor.Adaptors.ODataV4Adaptor" CrossDomain=true></SfDataManager>
        <ComboBoxFieldSettings Value="CustomerID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public string OrderValue { get; set; } = "TOMSP";
        public Query Query = new Query().Select(new List<string> { "CustomerID", "OrderID" }).Take(6).RequiresCount();
    
        public class OrderDetails
        {
            public int? OrderID { get; set; }
            public string CustomerID { get; set; }
            public int? EmployeeID { get; set; }
            public double? Freight { get; set; }
            public string ShipCity { get; set; }
            public bool Verified { get; set; }
            public DateTime? OrderDate { get; set; }
            public string ShipName { get; set; }
            public string ShipCountry { get; set; }
            public DateTime? ShippedDate { get; set; }
            public string ShipAddress { get; set; }
        }
    }

    Blazor ComboBox with OData v4 Adaptor

    Web API adaptor

    The Web API Adaptor is used to interact with Web API created under OData standards. The WebApiAdaptor is extended from the ODataAdaptor. Hence to use the WebApiAdaptor, the endpoint should understand the OData formatted queries sent along with the request.

  • CSHTML
  • @using Syncfusion.Blazor.Data
    @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="EmployeeData" Placeholder="Select a Employee" Query="@Query" @bind-Value="@EmployeeValue" Width="300px">
        <SfDataManager Url="https://ej2services.syncfusion.com/production/web-services/api/Employees" Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor" CrossDomain=true></SfDataManager>
        <ComboBoxFieldSettings Text="FirstName" Value="FirstName"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public string EmployeeValue { get; set; } = "Janet Leverling";
        public Query Query = new Query();
    
        public class EmployeeData
        {
            public int EmployeeID { get; set; }
            public string FirstName { get; set; }
            public string Designation { get; set; }
            public string Country { get; set; }
        }
    }

    Blazor ComboBox with Web API Adaptor

    Custom adaptor

    The SfDataManager has custom adaptor support which allows you to perform manual operations on the data. This can be utilized for implementing customize data binding and editing operations in the ComboBox component.

    For implementing custom data binding in the ComboBox, the DataAdaptor class is used. This abstract class acts as a base class for the custom adaptor.

    The DataAdaptor abstract class has both synchronous and asynchronous method signatures, which can be overridden in the custom adaptor. Following are the method signatures present in this class.

    public abstract class DataAdaptor
    {
        /// <summary>
        /// Performs data Read operation synchronously.
        /// </summary>
        public virtual object Read(DataManagerRequest dataManagerRequest, string key = null)
    
        /// <summary>
        /// Performs data Read operation asynchronously.
        /// </summary>
        public virtual Task<object> ReadAsync(DataManagerRequest dataManagerRequest, string key = null)
    }

    In custom Adaptor, the data binding operation can be performed in the ComboBox component by providing the custom adaptor class and overriding the Read or ReadAsync method of the DataAdaptor abstract class.

    The following sample code demonstrates implementing custom data binding using custom adaptor.

  • CSHTML
  • @using Syncfusion.Blazor
    @using Syncfusion.Blazor.Data
    @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="Orders">
        <SfDataManager AdaptorInstance="@typeof(CustomAdaptor)" Adaptor="Adaptors.CustomAdaptor"></SfDataManager>
        <ComboBoxFieldSettings Value="CustomerID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
    
        public class Orders
        {
            public Orders() { }
            public Orders(int OrderID, string CustomerID)
            {
                this.OrderID = OrderID;
                this.CustomerID = CustomerID;
            }
            public int OrderID { get; set; }
            public string CustomerID { get; set; }
        }
        public class CustomAdaptor : DataAdaptor
        {
            static readonly HttpClient client = new HttpClient();
            public static List<OrdersDetails> order = OrdersDetails.GetAllRecords();
            public override object Read(DataManagerRequest dm, string key = null)
            {
                IEnumerable<OrdersDetails> DataSource = order;
                if (dm.Search != null && dm.Search.Count > 0)
                {
                    DataSource = DataOperations.PerformSearching(DataSource, dm.Search);  //Search
                }
                if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting
                {
                    DataSource = DataOperations.PerformSorting(DataSource, dm.Sorted);
                }
                if (dm.Where != null && dm.Where.Count > 0) //Filtering
                {
                    DataSource = DataOperations.PerformFiltering(DataSource, dm.Where, dm.Where[0].Operator);
                }
                int count = DataSource.Cast<OrdersDetails>().Count();
                if (dm.Skip != 0)
                {
                    DataSource = DataOperations.PerformSkip(DataSource, dm.Skip);         //Paging
                }
                if (dm.Take != 0)
                {
                    DataSource = DataOperations.PerformTake(DataSource, dm.Take);
                }
                return dm.RequiresCounts ? new DataResult() { Result = DataSource, Count = count } : (object)DataSource;
            }
        }
    }

    Offline mode

    To avoid post back for every action, set the ComboBox to load all data on initialization and make the actions process on the client-side. To enable this behavior, use the Offline property of DataManager.

    The following example is for remote data binding and enabled offline mode.

  • CSHTML
  • @using Syncfusion.Blazor.Data
    @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="EmployeeData" Placeholder="Select a Employee" Query="@Query">
        <SfDataManager Url="https://ej2services.syncfusion.com/production/web-services/api/Employees" Offline=true Adaptor="Syncfusion.Blazor.Adaptors.WebApiAdaptor" CrossDomain=true></SfDataManager>
        <ComboBoxFieldSettings Text="FirstName" Value="EmployeeID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public Query Query = new Query();
    
        public class EmployeeData
        {
            public int EmployeeID { get; set; }
            public string FirstName { get; set; }
            public string Designation { get; set; }
            public string Country { get; set; }
        }
    }

    Blazor ComboBox with Offline mode

    Entity Framework

    Follow these steps to consume data from the Entity Framework in the ComboBox component.

    Create DBContext class

    The first step is to create a DBContext class called OrderContext to connect to a Microsoft SQL Server database.

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using EFDropDown.Shared.Models;
    
    namespace EFDropDown.Shared.DataAccess
    {
        public class OrderContext : DbContext
        {
            public virtual DbSet<Shared.Models.Order> Orders { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseSqlServer(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Blazor\DropDownList\EFDropDown\Shared\App_Data\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30");
                }
            }
        }
    }

    Create data access layer to perform data operation

    Now, create a class named OrderDataAccessLayer, which act as data access layer for retrieving the records from the database table.

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using EFDropDown.Shared.Models;
    
    namespace EFDropDown.Shared.DataAccess
    {
        public class OrderDataAccessLayer
        {
            OrderContext db = new OrderContext();
    
            //To Get all Orders details
            public DbSet<Order> GetAllOrders()
            {
                try
                {
                    return db.Orders;
                }
                catch
                {
                    throw;
                }
            }
        }
    }

    Creating web API controller

    A Web API Controller has to be created, which allows the ComboBox to directly consume data from the Entity Framework.

    using EFDropDown.Shared.DataAccess;
    using EFDropDown.Shared.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Web;
    using Microsoft.AspNetCore.Http;
    
    namespace EFDropDown.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        //TreeGrid
        public class DefaultController : ControllerBase
        {
            OrderDataAccessLayer db = new OrderDataAccessLayer();
            [HttpGet]
            public object Get()
            {
                IQueryable<Order> data = db.GetAllOrders().AsQueryable();
                var count = data.Count();
                var queryString = Request.Query;
                if (queryString.Keys.Contains("$inlinecount"))
                {
                    StringValues Skip;
                    StringValues Take;
                    int skip = (queryString.TryGetValue("$skip", out Skip)) ? Convert.ToInt32(Skip[0]) : 0;
                    int top = (queryString.TryGetValue("$top", out Take)) ? Convert.ToInt32(Take[0]) : data.Count();
                    return new { Items = data.Skip(skip).Take(top), Count = count };
                }
                else
                {
                    return data;
                }
             }
        }
    }

    Configure ComboBox component using Web API adaptor

    Now, configure the ComboBox using the SfDataManager to interact with the created Web API and consume the data appropriately. To interact with web API, use the WebApiAdaptor.

  • CSHTML
  • @using Syncfusion.Blazor
    @using Syncfusion.Blazor.Data
    @using Syncfusion.Blazor.DropDowns
    
    <SfComboBox TValue="string" TItem="Order" Placeholder="Select a Country">
        <SfDataManager Url="api/Default" Adaptor="Adaptors.WebApiAdaptor" CrossDomain="true"></SfDataManager>
        <ComboBoxFieldSettings Text="ShipCountry" Value="OrderID"></ComboBoxFieldSettings>
    </SfComboBox>
    
    @code {
        public class Order
        {
            public int? OrderID { get; set; }
            public string ShipCountry { get; set; }
        }
    }

    Adding new items

    Add the new item in the popup with the help of AddItemsAsync public method. This method will add a mentioned item in the ComboBox popup without affecting the data source items.

  • CSHTML
  • @using Syncfusion.Blazor.DropDowns
    @using Syncfusion.Blazor.Buttons
    
    <div>
        <SfComboBox @ref="comboObj" TValue="string" TItem="Games" Width="300px" Placeholder="Select a game" DataSource="@LocalData">
            <ComboBoxFieldSettings Value="ID" Text="Game"></ComboBoxFieldSettings>
        </SfComboBox>
    </div>
    <div>
        <SfButton Content="Click to add a new item" OnClick="OnBtnClick"></SfButton>
    </div>
    
    @code {
        SfComboBox<string, Games> comboObj;
    
        public class Games
        {
            public string ID { get; set; }
            public string Game { get; set; }
        }
        List<Games> LocalData = new List<Games> {
            new Games() { ID= "Game1", Game= "American Football" },
            new Games() { ID= "Game2", Game= "Badminton" },
            new Games() { ID= "Game3", Game= "Basketball" },
            new Games() { ID= "Game4", Game= "Cricket" },
            new Games() { ID= "Game5", Game= "Football" },
            new Games() { ID= "Game6", Game= "Golf" },
            new Games() { ID= "Game7", Game= "Hockey" },
            new Games() { ID= "Game8", Game= "Rugby"},
            new Games() { ID= "Game9", Game= "Snooker" },
        };
        public async Task OnBtnClick()
        {
            await this.comboObj.AddItemsAsync(new List<Games> { new Games() { ID = "Game11", Game = "Tennis" } });
        }
    }

    Blazor ComboBox with adding new Item