Remote Binding
The Telerik UI ListBox for ASP.NET MVC enables you to bind it to remote data by using a DataSource
configuration object. The component will receive the data from the remote endpoint by making an AJAX
request.
-
Create an action that returns the data as a
JSON
result.public class ListBoxController : Controller { public ActionResult GetCustomers() { var customers = Enumerable.Empty<CustomerViewModel>(); using (var northwind = GetContext()) { customers = northwind.Customers.Select(customer => new CustomerViewModel { CustomerID = customer.CustomerID, ContactName = customer.ContactName, }).ToList(); } return Json(customers, JsonRequestBehavior.AllowGet); } }
public class CustomerViewModel { public string CustomerID { get; set; } public string ContactName { get; set; } }
-
Define the ListBox to the View and configure its DataSource to use remote data.
@(Html.Kendo().ListBox() .Name("contacts") .DataTextField("ContactName") .DataValueField("CustomerID") .DataSource(source => source .Read(read => read.Action("GetCustomers", "ListBox")) // Specify the Read Action method. ) .ConnectWith("selected") .Toolbar(toolbar => { toolbar.Position(ListBoxToolbarPosition.Right); toolbar.Tools(tools => tools .MoveUp() .MoveDown() .TransferTo() .TransferFrom() .TransferAllTo() .TransferAllFrom() .Remove()); }) .BindTo(new List<CustomerViewModel>()) ) @(Html.Kendo().ListBox() .Name("selected") .DataTextField("ContactName") .DataValueField("CustomerID") .ConnectWith("contacts") .BindTo(new List<CustomerViewModel>()) )
By default, the ListBox will bind to the data during its initialization. To disable this behavior, set the AutoBind
option of the component to false
.
The example below demonstrates how to load the data in the ListBox when a button is clicked.
@(Html.Kendo().Button()
.Name("loadDataBtn")
.Content("Load the ListBox data")
.HtmlAttributes(new { type = "button" })
.Events(ev => ev.Click("onClick"))
)
<br/>
@(Html.Kendo().ListBox()
.Name("contacts")
.AutoBind(false)
.DataTextField("ContactName")
.DataValueField("CustomerID")
.DataSource(source => source
.Read(read => read.Action("GetCustomers", "ListBox")) // Specify the Read Action method.
)
.BindTo(new List<CustomerViewModel>())
)
<script>
function onClick() {
//Call the read() method of the dataSource to trigger the Read request.
$("#contacts").data("kendoListBox").dataSource.read();
}
</script>