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

Dropdownlist + Select Item

1 Answer 806 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Lars
Top achievements
Rank 1
Lars asked on 04 Nov 2015, 08:26 AM

Hi Everyone, 

 I have a question regarding the ASP.NET MVC Dropdownlist.

 I load my DDL with data from the controller like this. 

public JsonResult GetCountries()
{
    SelectList list = null;
    ServiceSession.CreateService<MemberService>((Service) =>
        {
            var country = Service.GetCountryCode​s();
            list = new SelectList(country, "Id", "Name", country.Where(e=>e.Name== "Danmark").First());
        });
 
    return Json(list, JsonRequestBehavior.AllowGet);
}
this result return a list of countries and add them to the DDL. 

@(Html.Kendo().DropDownListFor(m => m.CountryCode)
     .DataTextField("Text").DataValueField("Value").SelectedIndex(185).
     AutoBind(true).DataSource(dataSource => dataSource.Read(read =>
     { read.Action("GetCountries", "Member"); })))

Everything is fine, but how can I set the selectedIndex by the text and not the ID in the list?

I can't be sure that Denmark is always number 185. 

1 Answer, 1 is accepted

Sort by
0
Georgi Krustev
Telerik team
answered on 06 Nov 2015, 08:30 AM
Hello Lars,

In general, the DropDownList widget can select an item based on index or value. If you would like to select an item based on the text, then you will need to use the select method of the widget. Thus you can use a custom predicate and select the item that matches the custom condition:
@(Html.Kendo().DropDownListFor(m => m.CountryCode)
     .DataTextField("Text").DataValueField("Value").SelectedIndex(185).
     AutoBind(true).DataSource(dataSource => dataSource.Read(read =>
     { read.Action("GetCountries", "Member"); })))
<script>
  $(function() {
    var id = "@Html.IdFor(m => m.CountryCode)";
    var widget = $("#" + id).data("kendoDropDownList");
    var select = function() {
       widget.select([custom predicate here]);
    };
 
    if (!widget.dataSource.view().length) {
       widget.one("dataBound", function() { select(); }); //widget is not loaded yet
    } else {
       select();
    }
  });
</script>


Regards,
Georgi Krustev
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
DropDownList
Asked by
Lars
Top achievements
Rank 1
Answers by
Georgi Krustev
Telerik team
Share this question
or