简体   繁体   中英

Binding a KendoUI dropdownlist on demand

IF I have a kendo dropdownlist as follows

@(Html.Kendo().DropDownList()
      .Name("products")
      .DataTextField("ProductName")
      .DataValueField("ProductID")
      .DataSource(source => {
          source.Read(read =>
          {
              read.Action("GetProducts", "Home");
          }); 
      })
)

This loads when my page loads. Is there a way to code it such that it only loads when I invoke it to load via javscript?

Initialise DataSource on sever side without executing Read. For eg., .DataSource(source => {source.Type = "json"}). On Client side event handler, you can retrieve JSON data using ajax and attach to dropdownlist datasource as :

var dataretrieved = <ajax query here>
$("#products").data("kendoDropDownList").dataSource.data(dataretrieved );

Alternatively,

In server side code do not define datasource. In your client side event handler define the datasource of the dropdownlist. For eg.,

$("#products").data("kendoDropDownList").dataSource = new kendo.data.DataSource({
 type: "json",
 data: dataretrieved 
});

Note datatype is indicated as part of datasource definition.

If you wanted to load data first time when you open the dropdownlist, you can set AutoBind = false and add an OptionLabel like this:
@(Html.Kendo().DropDownList() .Name("products") .DataTextField("ProductName") .DataValueField("ProductID") .OptionLabel(new { ProductID = -1, ProductName= "Select Product"}) .DataSource(source => { source.Read(read => { read.Action("GetProducts", "Home"); }); }) .AutoBind(false) )

You have to be sure to use an option label with id and name , otherwise it will not be displayed.

Create one JS function and put this code inside in it. and call that function when you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM