9

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!

Lopo
  • 936
  • 2
  • 11
  • 18

1 Answers1

10

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)
)
Lopo
  • 936
  • 2
  • 11
  • 18
  • it is showing tht it does not contain defination of multiselect...why is tht?? – Neel May 31 '13 at 05:04
  • Probably you are using an older version of Kendo UI..? – Lopo Aug 13 '13 at 14:38
  • I have similar issue with this difference that I'm using Ajax Binding and I've set the MaxSelectedItem to 1. And in my Model the equivalent field is type of long, not an IEnumberable or a collection. Any idea for me? – Akbari Jul 11 '15 at 05:47
  • I just want to say that this is literally the simplest example of it just "working" I've ever seen. In my usage, i pass it an IList of ints as the model field. – John Lord Oct 30 '19 at 05:02