Data Binding in Blazor MultiSelect Dropdown Component
4 Nov 202524 minutes to read
The MultiSelect loads data from either local data sources or remote data services. Use the DataSource property to bind local data, or use the DataManager to bind remote data.
- TItem - Defines the type of the items in the MultiSelect data source.
Binding local data
The MultiSelect 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.
@using Syncfusion.Blazor.DropDowns
@foreach (var SelectedValue in MultiVal)
{
<p>MultiSelect value is:<strong>@SelectedValue</strong></p>
}
<SfMultiSelect Placeholder="e.g. Australia" @bind-Value="@MultiVal" DataSource="@Countries">
<MultiSelectFieldSettings Value="Name"></MultiSelectFieldSettings>
</SfMultiSelect>
@code {
public string[] MultiVal { get; set; } = new string[] { };
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 is triggered when the data source is populated in the popup list.
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TItem="GameFields" TValue="string[]" DataSource="@Games">
<MultiSelectEvents TItem="GameFields" TValue="string[]" DataBound="@DataBoundHandler"></MultiSelectEvents>
<MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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 data to the MultiSelect as an array or list of items of type string, int, double, or bool.
The following example demonstrates binding an array of string values to the MultiSelect component.
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="string[]" TItem="string" Placeholder="Select a game" DataSource="@data" @bind-Value="MyItem" Width="300px"></SfMultiSelect>
@code{
List<string> data = new List<string>() {"One", "Two", "Three"};
public string[] MyItem { get; set; } = ["Two"];
}
The following example demonstrates binding an array of integer values to the MultiSelect component.
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="int[]?" TItem="int?" Placeholder="Select a game" DataSource="@data" @bind-Value="MyItem" Width="300px"></SfMultiSelect>
@code{
List<int?> data = new List<int?>() { 100, 200, 300 };
public int[]? MyItem { get; set; } = [300];
}
Complex data type
The MultiSelect can generate list items from an array of complex objects. Map the appropriate fields to the Fields property.
In the following example, the Code.ID field and Country.CountryID field from the complex data are mapped to the Value and Text fields, respectively.
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="string[]" TItem="Complex" Placeholder="e.g. Select a country" DataSource="@LocalData">
<MultiSelectFieldSettings Text="Country.CountryID" Value="Code.ID"></MultiSelectFieldSettings>
</SfMultiSelect>
@code {
public List<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;
}
}
}
Expando object binding
Bind ExpandoObject data to the MultiSelect component. In the following example, the ExpandoObject is bound to a collection of vehicles.
@using Syncfusion.Blazor.DropDowns
@using System.Dynamic
<SfMultiSelect TItem="ExpandoObject" TValue="string[]" PopupHeight="230px" Placeholder="Select a vehicle" DataSource="@VehicleData">
<MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>
@code{
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>();
}
}
Observable collection binding
Bind ObservableCollection data to the MultiSelect component. In the following example, the Observable Data is bound to a collection of colors data.
@using Syncfusion.Blazor.DropDowns
@using System.Collections.ObjectModel;
<SfMultiSelect TValue="string[]" TItem="Colors" PopupHeight="230px" Placeholder="Select a color" DataSource="@ColorsData">
<MultiSelectFieldSettings Text="Color" Value="Code"></MultiSelectFieldSettings>
</SfMultiSelect>
@code {
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" }
};
}
Dynamic object binding
Bind the DynamicObject data to the MultiSelect component. In the following example, the DynamicObject is bound to collection of customer data.
@using Syncfusion.Blazor.DropDowns
@using System.Dynamic
<SfMultiSelect TValue="string[]" TItem="DynamicDictionary" Placeholder="Select a name" DataSource="@Orders">
<MultiSelectFieldSettings Text="CustomerName" Value="CustomerName"></MultiSelectFieldSettings>
</SfMultiSelect>
@code{
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;
}
}
}
Enum data binding
Convert enum values into a list of strings and bind them to the DataSource property of the SfMultiSelect component to bind enum types to the MultiSelect Dropdown component.
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="List<string>" TItem="string" Placeholder="Select a color" DataSource="@MultiSelectDataSource"
@bind-Value="SelectedValues">
<MultiSelectFieldSettings Value="Value" Text="Text"></MultiSelectFieldSettings>
</SfMultiSelect>
@if (SelectedValues != null)
{
<p>Selected Colors: @string.Join(", ", SelectedValues)</p>
}
@code {
public enum Color
{
Red,
Blue,
Green,
Yellow
}
public class EnumModel
{
public Color Value { get; set; }
public string Text { get; set; }
}
private List<string> MultiSelectDataSource { get; set; } = new List<string>();
private List<string> SelectedValues { get; set; }
protected override void OnInitialized()
{
MultiSelectDataSource = Enum.GetNames(typeof(Color)).ToList();
SelectedValues = new List<string> { Enum.GetName(typeof(Color), 2) };
}
}
ValueTuple data binding
Bind ValueTuple data to the MultiSelect component. The following example shows how to obtain a string value from enumeration data by using ValueTuple.
@using Syncfusion.Blazor.DropDowns;
<SfMultiSelect TItem="(DayOfWeek, string)" Width="250px" TValue="DayOfWeek[]"
DataSource="@(Enum.GetValues<DayOfWeek>().Select(e => (e, e.ToString())))">
<MultiSelectFieldSettings Value="Item1" Text="Item2" />
</SfMultiSelect>
Binding remote data
The MultiSelect supports retrieving data from remote services by using the DataManager component. Use the Query property to fetch data from the server and bind it to the MultiSelect.
- DataManager.Url - Defines the service endpoint to fetch data.
- DataManager.Adaptor - Specifies the adaptor. By default, the ODataAdaptor is used when a URL is provided; choose an adaptor that matches your service endpoint.
- The Syncfusion.Blazor.Data package provides predefined adaptors designed to interact with specific service endpoints.
OnActionBegin event
The OnActionBegin event is triggered before fetching data from the remote server.
@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Data
<SfMultiSelect TValue="string" TItem="OrderDetails" Query="@RemoteDataQuery">
<SfDataManager Url="https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders" CrossDomain="true" Adaptor="Syncfusion.Blazor.Adaptors.ODataAdaptor"></SfDataManager>
<MultiSelectEvents TValue="string" TItem="OrderDetails" OnActionBegin="@OnActionBeginhandler"></MultiSelectEvents>
<MultiSelectFieldSettings Text="CustomerID" Value="CustomerID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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 is triggered after data is successfully fetched from the remote server.
@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Data
<SfMultiSelect TValue="string" TItem="OrderDetails" Query="@RemoteDataQuery">
<SfDataManager Url="https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders" CrossDomain="true" Adaptor="Syncfusion.Blazor.Adaptors.ODataAdaptor"></SfDataManager>
<MultiSelectEvents TValue="string" TItem="OrderDetails" OnActionComplete="@OnActionCompletehandler"></MultiSelectEvents>
<MultiSelectFieldSettings Text="CustomerID" Value="CustomerID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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 is triggered when the data fetch request fails.
@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Data
<SfMultiSelect TValue="string" TItem="OrderDetails" Query="@RemoteDataQuery">
<SfDataManager Url="https://js.syncfusion.com/demos/ejServices/Wcf/Northwind.svc/Orders" CrossDomain="true" Adaptor="Syncfusion.Blazor.Adaptors.ODataAdaptor"></SfDataManager>
<MultiSelectEvents TValue="string" TItem="OrderDetails" OnActionFailure="@OnActionFailurehandler"></MultiSelectEvents>
<MultiSelectFieldSettings Text="CustomerID" Value="CustomerID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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 the Customers table of the Northwind data service.
@using Syncfusion.Blazor.Data
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="string[]" TItem="OrderDetails" Placeholder="Select a customer" Query="@Query">
<SfDataManager Url="https://services.odata.org/V4/Northwind/Northwind.svc/Orders" Adaptor="Adaptors.ODataV4Adaptor" CrossDomain=true></SfDataManager>
<MultiSelectFieldSettings Text="CustomerID" Value="OrderID"></MultiSelectFieldSettings>
</SfMultiSelect>
@code {
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; }
}
}
Web API adaptor
The Web API adaptor is used to interact with Web API endpoints that follow OData conventions. The WebApiAdaptor extends the ODataAdaptor. To use WebApiAdaptor, the endpoint must understand OData-formatted queries sent with the request.
@using Syncfusion.Blazor.Data
@using Syncfusion.Blazor
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="string[]" Placeholder="Select a Employee" Query="@Query">
<SfDataManager Url="https://ej2services.syncfusion.com/production/web-services/api/Employees" Adaptor="Adaptors.WebApiAdaptor" CrossDomain=true></SfDataManager>
<MultiSelectFieldSettings Text="FirstName" Value="EmployeeID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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; }
}
}
Custom adaptor
The SfDataManager supports custom adaptors to perform manual operations on data. This can be used to implement custom data binding and editing operations in the MultiSelect component.
For custom data binding in the MultiSelect, use the DataAdaptor class. This abstract class acts as the base for a custom adaptor.
The DataAdaptor abstract class provides synchronous and asynchronous method signatures that can be overridden in the custom adaptor.
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)
}Custom data binding can be performed in the MultiSelect component by providing the custom adaptor class and overriding the Read or ReadAsync method of the DataAdaptor abstract class.
The following example demonstrates implementing custom data binding using a custom adaptor.
<SfMultiSelect TValue="string[]" TItem="Orders">
<SfDataManager AdaptorInstance="@typeof(CustomAdaptor)" Adaptor="Adaptors.CustomAdaptor"></SfDataManager>
<MultiSelectFieldSettings Value="CustomerID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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
{
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 a postback for every action, load all data during initialization and process actions on the client. To enable this behavior, set the Offline property of DataManager to true.
The following example demonstrates remote data binding with offline mode enabled.
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Data
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="string[]" TItem="EmployeeData" Placeholder="Select a Employee" Query="@Query">
<SfDataManager Url="https://ej2services.syncfusion.com/production/web-services/api/Employees" Adaptor="Adaptors.WebApiAdaptor" CrossDomain=true Offline=true></SfDataManager>
<MultiSelectFieldSettings Text="FirstName" Value="EmployeeID"></MultiSelectFieldSettings>
</SfMultiSelect>
@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; }
}
}
Entity Framework
Follow these steps to consume data from Entity Framework in the MultiSelect component.
Create DBContext class
Create a DbContext class named 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
Create a class named OrderDataAccessLayer that acts as the data access layer for retrieving 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
Create a Web API controller that allows the MultiSelect to consume data directly from 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 MultiSelect component using Web API adaptor
Configure the MultiSelect by using the SfDataManager to interact with the created Web API and consume the data appropriately. To interact with web API, use the WebApiAdaptor.
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Data
@using Syncfusion.Blazor.DropDowns
<SfMultiSelect TValue="string[]" TItem="Order" Placeholder="Select a Country">
<SfDataManager Url="api/Default" Adaptor="Adaptors.WebApiAdaptor" CrossDomain="true"></SfDataManager>
<MultiSelectFieldSettings Text="ShipCountry" Value="OrderID"></MultiSelectFieldSettings>
</SfMultiSelect>
@code{
public class Order
{
public int? OrderID { get; set; }
public string[] ShipCountry { get; set; }
}
}Adding new items
Add new items to the popup by using the AddItemsAsync method. This method adds the specified items to the MultiSelect popup without modifying the data source.
<div>
<SfMultiSelect @ref="multiselectObj" TValue="string[]" TItem="Games" Width="300px" Placeholder="Select a game" DataSource="@LocalData">
<MultiSelectFieldSettings Value="ID" Text="Game"></MultiSelectFieldSettings>
</SfMultiSelect>
</div>
<div>
<SfButton Content="Click to add a new item" OnClick="OnBtnClick"></SfButton>
</div>
@code {
SfMultiSelect<string[], Games> multiselectObj;
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.multiselectObj.AddItemsAsync(new List<Games> { new Games() { ID = "Game11", Game = "Tennis" } });
}
}
Customizing the Change Event
By default, the MultiSelect fires the Change event when the component loses focus. To fire the Change event whenever a value is selected or removed, set the EnableChangeOnBlur property to false. The default value of EnableChangeOnBlur is true.
@using Syncfusion.Blazor.DropDowns;
<SfMultiSelect TValue="string[]" TItem="Games" Placeholder="Favorite Sports" DataSource="@LocalData" EnableChangeOnBlur="@EnableChangeOnBlur">
<MultiSelectEvents TItem="Games" TValue="string[]" ValueChange="@ValueChangeHandler"></MultiSelectEvents>
<MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>
@code {
public class Games
{
public string ID { get; set; }
public string Text { get; set; }
}
List<Games> LocalData = new List<Games> {
new Games() { ID= "Game1", Text= "American Football" },
new Games() { ID= "Game2", Text= "Badminton" },
new Games() { ID= "Game3", Text= "Basketball" },
new Games() { ID= "Game4", Text= "Cricket" },
new Games() { ID= "Game5", Text= "Football" },
new Games() { ID= "Game6", Text= "Golf" },
new Games() { ID= "Game7", Text= "Hockey" },
new Games() { ID= "Game8", Text= "Rugby"},
new Games() { ID= "Game9", Text= "Snooker" },
new Games() { ID= "Game10", Text= "Tennis"},
};
public bool EnableChangeOnBlur { get; set; } = false;
private void ValueChangeHandler()
{
// Here you can customize your code
}
}Get Data by value
Retrieve the data item corresponding to a specified value by using the GetDataByValue(TValue) method from an instance of the MultiSelect. For example, bind a button click to call GetDataByValue(TValue) on the component instance and return the item data for that value.
@using Syncfusion.Blazor.DropDowns;
<div class=button>
<button @onclick="GetDataByValue">Button</button>
</div>
<div class=content>
<SfMultiSelect @ref="MultiSelectObj" TValue="string[]" TItem="Games" Placeholder="Favorite Sports" DataSource="@LocalData" ShowDropDownIcon="true" @bind-Value="@GameValue">
<MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>
</div>
@code {
SfMultiSelect<string[],Games> MultiSelectObj;
public class Games
{
public string ID { get; set; }
public string Text { get; set; }
}
List<Games> LocalData = new List<Games> {
new Games() { ID= "Game1", Text= "American Football" },
new Games() { ID= "Game2", Text= "Badminton" },
new Games() { ID= "Game3", Text= "Basketball" },
new Games() { ID= "Game4", Text= "Cricket" },
new Games() { ID= "Game5", Text= "Football" },
new Games() { ID= "Game6", Text= "Golf" },
new Games() { ID= "Game7", Text= "Hockey" },
new Games() { ID= "Game8", Text= "Rugby"},
new Games() { ID= "Game9", Text= "Snooker" },
new Games() { ID= "Game10", Text= "Tennis"},
};
public string[] GameValue { get; set; } = { "Game5"};
public async void GetDataByValue()
{
var val = this.MultiSelectObj.Value;
var Data = await this.MultiSelectObj.GetDataByValueAsync(val);
Console.WriteLine (Data[0].ID.ToString());
Console.WriteLine (Data[0].Text.ToString());
}
}
<style>
.content{
margin-top: 5px;
}
</style>Get List Item
Retrieve the list items from the dropdown list by using the GetItemsAsync() method through an instance of the dropdown list. You can bind the click event of a button to the GetItemsAsync() method of the dropdown list instance. When the button is clicked, it will trigger the GetItemsAsync() method on the dropdown list and return the list items.
@using Syncfusion.Blazor.DropDowns;
<div class=button>
<button @onclick="GetItems">Button</button>
</div>
<div class=content>
<SfMultiSelect @ref="MultiSelectObj" TValue="string[]" TItem="Games" Placeholder="Favorite Sports" DataSource="@LocalData" ShowDropDownIcon="true" @bind-Value="@GameValue" FilterType="FilterType.StartsWith">
<MultiSelectFieldSettings Text="Text" Value="ID"></MultiSelectFieldSettings>
</SfMultiSelect>
</div>
@code {
SfMultiSelect<string[],Games> MultiSelectObj;
public class Games
{
public string ID { get; set; }
public string Text { get; set; }
}
List<Games> LocalData = new List<Games> {
new Games() { ID= "Game1", Text= "American Football" },
new Games() { ID= "Game2", Text= "Badminton" },
new Games() { ID= "Game3", Text= "Basketball" },
new Games() { ID= "Game4", Text= "Cricket" },
new Games() { ID= "Game5", Text= "Football" },
new Games() { ID= "Game6", Text= "Golf" },
new Games() { ID= "Game7", Text= "Hockey" },
new Games() { ID= "Game8", Text= "Rugby"},
new Games() { ID= "Game9", Text= "Snooker" },
new Games() { ID= "Game10", Text= "Tennis"},
};
public string[] GameValue { get; set; } = { "Game5"};
public async Task GetItems () {
IEnumerable<Games> Items = await this.MultiSelectObj.GetItemsAsync();
foreach(var listItem in Items)
{
Console.WriteLine (listItem.ID);
Console.WriteLine (listItem.Text);
}
}
}
<style>
.content{
margin-top: 5px;
}
</style>