Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kendo Multiselect: Selected values from binded model are not initialized

Update:

To shorten the question:

How to bind a SelectList to a Kendo UI MultiSelect Widget using Razor?

Original question:

In an ASP.NET MVC 4 Application, I am trying to get the Kendo Multiselect working. I am binding the Multiselect widget to my model/viewmodel but the init values are not being used. Selecting and so works perfectly.

Model:

public class Data
{
    public IEnumerable<int> SelectedStudents{ get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Controller:

List<Student> students = new List<Student>();
students.Add(new Baumaterial { Id = 1, Name = "Francis" });
students.Add(new Baumaterial { Id = 2, Name = "Jorge" });
students.Add(new Baumaterial { Id = 3, Name = "Drew" });
students.Add(new Baumaterial { Id = 4, Name = "Juan" });

ViewBag.Students= new SelectList(students, "Id", "Name");
Data data = new Data { SelectedStudents = new List<int>{2, 4} };

return PartialView(data);

View: Standard-HTML works perfectly!!

<div class="form-label">
    @Html.LabelFor(model => model.SelectedStudents)
</div>
<div class="form-field large">
    @Html.ListBoxFor(model => model.SelectedStudents, (SelectList)ViewBag.Students)
</div>
<div class="form-message">
    @Html.ValidationMessageFor(model => model.SelectedStudents)
</div>

View: Kendo Multiselect not working --> Multiselect is empty (no preselections), but i can select values perfectly

<div class="form-label">
    @Html.LabelFor(model => model.SelectedStudents)
</div>
<div class="form-field large">
    @(Html.Kendo().MultiSelectFor(model => model.SelectedStudents)
        .BindTo((SelectList)ViewBag.Students)
    )
</div>
<div class="form-message">
    @Html.ValidationMessageFor(model => model.SelectedStudents)
</div>

What I am doing wrong? Thanks for any advice!

like image 709
Lopo Avatar asked May 14 '13 13:05

Lopo


1 Answers

Using MultiSelect() instead of MultiSelectFor() and pass the preselection as a list of strings instead of a list of integers.

@(Html.Kendo().MultiSelect()
    .Name("SelectedStudents")
    .BindTo(new SelectList(ViewBag.Students, "Id", "Name"))
    .Value(Model.SelectedStudents)
)
like image 78
Lopo Avatar answered Nov 09 '22 20:11

Lopo