Dropdownlist + Select Item

2 posts, 0 answers
  1. Lars
    Lars  avatar
    11 posts
    Member since:
    Jul 2015

    Posted 04 Nov 2015 Link to this post

    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. 

  2. Georgi Krustev
    Admin
    Georgi Krustev avatar
    3707 posts

    Posted 06 Nov 2015 Link to this post

    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
  3. UI for ASP.NET MVC is VS 2017 Ready
Back to Top