kendo-uikendo-dropdown

How to set default value in Kendo DropDownList


I have a Kendo DropDownList, but strangely enough I can not set its initial value.

Html.Kendo().DropDownList()
    .Name("PersonalCoachName")
    .BindTo(new SelectList((List<string>)ViewData["coachResources"]))
    .HtmlAttributes(new { style = "font-size:8pt;" })

ViewData["coachResources"] is a List of string type. Regardless I use

.BindTo(new SelectList((List<string>)ViewData["coachResources"], "Default"))
or 
.SelectedIndex(3)

DropDownList does not change it value and only display the 1st value in the list. I need help on this. Thanks.


Solution

  • Use the Value-method. See example code below.

    @(Html.Kendo().DropDownList()
          .Name("DropDownListName")
          .DataTextField("Text")
          .DataValueField("Value")
          .BindTo(model.DropDownListItems)
          .Value(model.Selected)
          )
    

    EDIT: DropDownList needs to be bind to List<SelectListItem> and it can be initialized as seen below.

    var items = new List<SelectListItem>
    {
        new SelectListItem { Text = "Item0", Value = "0" }, 
        new SelectListItem { Text = "Item1", Value = "1" } 
    };
    

    In addition, I would recommend to use MVVM to attach it to view.

    public class DropDownViewModel
    {
        public String Selected;
        public List<SelectListItem> DropDownListItems;
    
        public DropDownViewModel(String selected, List<SelectListItem> dropDownListItems)
        {
            Selected = selected;
            DropDownListItems = dropDownListItems;
        }
    }