Neha Agrawal
Neha Agrawal

Reputation: 155

How to bind kendo dropdownlist to model (strongly typed view)

I wanted to bind two kendo dropdownlists to the strongly typed view (@model) in a cascading manner. This model is a List<Enterprise>:

class Enterprise
{
    string EnterpriseId {get; set;}  //Bind this to first dropdown
    List<FinYear> FinancialYears {get; set;}
}


class FinYear
{
    string FinancialYear {get; set;} //Bind this to second dropdown
    string EnterpriseId [get; set;}
}        

How to properly get data from List<FinYear> into the dropdown?

Upvotes: 4

Views: 11731

Answers (2)

logan gilley
logan gilley

Reputation: 301

When you pass a strongly typed model to the view if you name a kendo control the same as the property name that your wanting to bind to then it will automatically bind the stored value to the control as the view is loaded.

@model TestProject.Models.TestModel

@(Html.Kendo().ComboBox()
.Name("Model property you want to bind")
.Text(Model.TestPropertyText) //Display text of stored value in field
.Placeholder("Place holder text")
//The DataText and DataValue fields bind your listItem's text and values
.DataTextField("TestPropertyText")
.DataValueField("TestPropertyId")
.AutoBind(false)
//Now I used a datasource from a server side controller action but 
//you should be able to do this also by the .BindTo(Model) as well
.DataSource(d => 
{ 
   d.Read(r => r.Action("GetTestModel_Read","TestController"));
}))

Upvotes: 2

Neha Agrawal
Neha Agrawal

Reputation: 155

The solution to making it work: I used a combination of javascript and html

HTML

// first dropdown
@(Html.Kendo.DropDownList()
.Name("entDDL")
.DataTextField("EnterpriseId")
.DataValueField("EnterpriseId")
.BindTo(Model)
.Events(e => e.Select("on_select")))

<input id="fDDL"> // second dropdown

Javascript

<script>
//on document ready
$(document).ready(function (){
    var finYearDDL = $("#fDDL").kendoDropDownList({}).data("kendoDropDownList");});

function on_select(e) {
    var dataItem = this.dataItem(e.item.index());
    dataItem = JSON.parse(JSON.stringify(dataItem.FinancialYears));
    var source = new kendo.data.DataSource({data : dataItem});

    // finyear dropdown
    var bind = $("#fDDL").kendoDropDownList({
        dataSource : source,
        datatextField : "FinancialYear",
        dataValueField : "FinancialYear",
        optionLabel : "Select..."});
}

Upvotes: 5

Related Questions