Adding an Item in a DropDownList
Environment
Product | Telerik UI for ASP.NET MVC DropDownList |
Progress Telerik UI for ASP.NET MVC version | Created with the 2022.2.510 version |
Description
How can I add a new item if it doesn't exist when working with the Telerik UI for ASP.NET MVC DropDownList?
Solution
- Create a separate
Custom
DataSource and specify the action method for the.Create()
method. - Set the filter type for the DropDownList through the
.Filter()
. - Specify a
NoDataTemplate
which will display an add confirmation dialog. - Inside the template, create a button and attach a handler that passes both the widget
id
and inputvalue
. -
Sync
the data to update the records.
@using Telerik.Examples.Mvc.Models
@(Html.Kendo().DataSource<Location>()
.Name("customDataSource")
.Custom(c=>c
.Transport(transport=>transport
.Read(read => read.Action("GetLocations", "AddItem"))
.Create(create => create.Action("CreateLocation", "AddItem"))
)
.Schema(s=>s
.Model(m=>
{
m.Id("Id");
m.Field(f=>f.Id);
m.Field(f=>f.Name);
})
)
)
)
@(Html.Kendo().DropDownList()
.Name("dropDownList")
.DataTextField("Name")
.DataValueField("Id")
.NoDataTemplateId("noDataTemplate")
.Filter(FilterType.StartsWith)
.DataSource("customDataSource")
.HtmlAttributes(new { style = "width: 100%" })
)
public class AddItemController : Controller
{
public ActionResult AddItem()
{
return View("~/Views/DropDownList/AddItem.cshtml");
}
public ActionResult GetLocations()
{
IEnumerable<Location> locations = LocationsData();
return Json(locations, JsonRequestBehavior.AllowGet);
}
public ActionResult CreateLocation(Location location)
{
return Json(new[] { location });
}
private List<Location> LocationsData()
{
return new List<Location>()
{
new Location() { Id = 1, Name = "London" },
new Location() { Id = 2, Name = "Paris" },
new Location() { Id = 3, Name = "Sofia" }
};
}
}
<script id="noDataTemplate" type="text/x-kendo-tmpl">
<button class="k-button k-button-solid k-button-md k-rounded-md k-button-solid-base" onclick="addNew('#: instance.element[0]. id #', '#: instance.filterInput.val() #')">Add new item</button>
</script>
<script>
function addNew(widgetId, value) {
var widget = $("#" + widgetId).getKendoDropDownList(); //get the reference of the dropdownlist
var dataSource = widget.dataSource;
if (confirm("Are you sure?")) {
dataSource.add({ //add a new item to the datasource
Id: 0,
Name: value
});
dataSource.one("sync", function () {
widget.select(dataSource.view().length - 1);
});
dataSource.filter({});
dataSource.sync(); //sync the data
}
};
</script>
For the complete implementation of the suggested approach, refer to this GitHub Project.