How to add item in ASP.NET CORE DropDownList
21 Aug 20264 minutes to read
You can insert an item at a specific position by passing the target index. If you add a new item without specifying an index, it will be appended as the last item.
<div class="control-wrapper">
<div id="default" style='padding-top:75px;'>
<ejs-dropdownlist id="games" dataSource="@ViewBag.data" placeholder="Select a game" index="2" popupHeight="220px">
<e-dropdownlist-fields value="Game"></e-dropdownlist-fields>
</ejs-dropdownlist>
</div>
</div>
<div>
<ejs-button id="first" content="add item (Hockey) in first"></ejs-button>
</div>
<div>
<ejs-button id="between" content="add item (Golf) in between"></ejs-button>
</div>
<div>
<ejs-button id="last" content="add item (Cricket) in last"></ejs-button>
</div>
<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 = "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;
}
}
}