Search results

Add Items in ASP.NET MVC ListBox control

To add an item or multiple items, addItems method can be used. In the following example, the Bugatti Veyron Super Sport and SSC Ultimate Aero items will be added while clicking Add Items button.

razor
additem.cs
@Html.EJS().ListBox("listbox").DataSource((IEnumerable<object>)ViewBag.data).Render()
<button class="e-btn" id="additem">Add Items</button>

<script>
    document.getElementById("additem").onclick = function () {
        var items = ['Bugatti Veyron Super Sport', 'SSC Ultimate Aero'];
        var listboxobj = document.getElementById("listbox").ej2_instances[0];
        if (!listboxobj.getDataByValue('Bugatti Veyron Super Sport')) {
            listboxobj.addItems(items);
        }
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class ListBoxController : Controller
    {
        public IActionResult additem()
        {
            ViewBag.data = new string[] { "BadmHennessey Venominton", "Bugatti Chiron", "Koenigsegg CCR", "McLaren F1", "Aston Martin One- 77", "Jaguar XJ220" };
            return View();
        }
    }
}