How to add item in ASP.NET MVC 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.
@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("220px").DataSource((IEnumerable<object>)ViewBag.data).Index(2).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 = "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;
}
}
}