Add item in between in DropDownList

7 Jun 20244 minutes to read

You can add item in between based on item index. If you add new item without item index, item will be added as last item in list.

@Html.EJS().Button("first").Content("add item (Hockey) in first").Render()
@Html.EJS().Button("between").Content("add item (Golf) in Between").Render()
@Html.EJS().Button("last").Content("add item (Cricket) in last").Render()
@Html.EJS().DropDownList("games").Placeholder("Select a game").PopupHeight("200px").DataSource((IEnumerable<object>)ViewBag.data).Fields(new Syncfusion.EJ2.DropDowns.DropDownListFieldSettings { Value = "Game" }).Render()

<script>
    document.getElementById('first').onclick = () => {
        var dropObject = document.getElementById("games").ej2_instances[0];
        dropObject.addItem({ Game: 'Hockey' }, 0);
    };
    // add item in between
    document.getElementById('between').onclick = () => {
        var dropObject = document.getElementById("games").ej2_instances[0];
        dropObject.addItem({ Game: "Golf" }, 2);
    };
    // add item at last
    document.getElementById('last').onclick = () => {
        var dropObject = document.getElementById("games").ej2_instances[0];
        dropObject.addItem({ Game: "Cricket" });
    };
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class GameList
    {
        public string Id { get; set; }
        public string Game { get; set; }

        public List<GameList> GameLists()
        {
            List<GameList> game = new List<GameList>();
            game.Add(new GameList { Id = "Game1", Game = "American Football" });
            game.Add(new GameList { Id = "Game2", Game = "Badminton" });
            game.Add(new GameList { Id = "Game3", Game = "Basketball" });
            game.Add(new GameList { Id = "Game3", Game = "Basketball" });
            game.Add(new GameList { Id = "Game4", Game = "Cricket" });
            game.Add(new GameList { Id = "Game5", Game = "Football" });
            game.Add(new GameList { Id = "Game6", Game = "Golf" });
            game.Add(new GameList { Id = "Game7", Game = "Hockey" });
            game.Add(new GameList { Id = "Game8", Game = "Rugby" });
            game.Add(new GameList { Id = "Game9", Game = "Snooker" });
            game.Add(new GameList { Id = "Game10", Game = "Tennis" });
            return game;
        }
    }
}