This is a migrated thread and some comments may be shown as answers.

Specify Selected Item when get data remotely

1 Answer 260 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
John
Top achievements
Rank 1
John asked on 21 Feb 2015, 02:02 AM
Using the ASP.NET MVC Extensions, I am loading a DropDownList with data from the server.
How can I also pass down from the server which of the items in the DDL I would like to be selected? I always need to have at least one item selected and it will most likely not be the first item in the list. Until I fetch the data for the current user, I will not know which item should be selected.

This is my current code:

@(Html.Kendo().DropDownList()
      .Name("companies")
      .HtmlAttributes(new { style = "width:300px" })
      .DataTextField("CompanyName")
      .DataValueField("CompanyId")
      .Filter("contains")
      .DataSource(source =>
          {
              source.Read(read => { read.Action("GetCompanies", "CommonAjax"); })
                  .ServerFiltering(true);
          })
      .Deferred()
)

Thanks,
--John

1 Answer, 1 is accepted

Sort by
0
Accepted
Georgi Krustev
Telerik team
answered on 24 Feb 2015, 01:24 PM
Hello John,

In general, the widget has Value method that allows to set the selected value:
@(Html.Kendo().DropDownList()
       .Value("selected value")
....

If you would like to get the selected value from the server during the Ajax request, then I can think of two possible ways to accomplish your goal:
  • Make a second request in order to get the widget's value from server then set the value using its value method
  • The company object should have a field that marks it as selected.​ With this information, you can wire the DataBound event of the data source, loop though the data items and once the selected item is found to select the value of the widget accordingly:
    //Widget initialization is here
    <script>
      $(function() {
        var dropdownlist = $("#companies").data("kendoDropDownList");
     
        //bind event only once
        dropdownlist.one("dataBound", function() {
          var data = this.dataSource.view();
     
          for (var idx = 0; idx < data.length; idx++) {
             if (data[idx] is selected) {
               this.value(data[idx].CompanyId);
               break;
            }
          }
        });
      });
    </script>

Regards,
Georgi Krustev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
DropDownList
Asked by
John
Top achievements
Rank 1
Answers by
Georgi Krustev
Telerik team
Share this question
or