Jevgenij Nekrasov
Jevgenij Nekrasov

Reputation: 2760

Kendo UI MultiSelect post binded values to the controller

I have multiselect widget

@(Html.Kendo().MultiSelect()
      .Name("SupportedLanguages")
      .Filter(FilterType.Contains)
      .Placeholder("Select supported languages...")
      .BindTo((System.Collections.IEnumerable)ViewData["supportedLanguages"]))

supportedLanguages is just array of strings

return new[] { "pl", "en", "sv" };

MultiSelect bind values correctly and I can select languages from the list, but when I post these values back to the controller I get such post parameters

SupportedLanguages[]=pl&SupportedLanguages[]=sv&SupportedLanguages[]=en

so MVC binder cannot bind these values to my ViewModel correctly.

ViewModel is just a simple class with one property

public List<string> SupportedLanguages { get; set; }

What I am doing wrong?

Upvotes: 1

Views: 5728

Answers (1)

Vladislav Kostenko
Vladislav Kostenko

Reputation: 1205

I don't know the reason of such implementation, but here is workaround for the problem. Example for MultiSelect inside grid with Ajax binding:

//Model
public class Model
{
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    /*MultiSelect for this property*/
    public IEnumerable<ChildModel> Children { get; set; }        
}

//View
@Html.Kendo().Grid<Model>()
  .Name("Grid")
  ...
  .DataSource(cfg => cfg
        .Ajax()
        .PageSize(20)
        .Model(c => c.Id(e => e.Id))
        .Update(c => c.Action("GridUpdate", "MyController").Data("getUpdateData"))
)

//JS
var getUpdateData = function(data) {
    MultiSelectHelpers.serialize(data);
};

var MultiSelectHelpers = {
    serialize: function (data) {
        for (var property in data) {
            if ($.isArray(data[property])) {
                this.serializeArray(property, data[property], data);
            }
        }
    },
    serializeArray: function (prefix, array, result) {
        for (var i = 0; i < array.length; i++) {
            if ($.isPlainObject(array[i])) {
                for (var property in array[i]) {
                    result[prefix + "[" + i + "]." + property] = array[i][property];
                }
            }
            else {
                result[prefix + "[" + i + "]"] = array[i];
            }
        }
    }
}

Upvotes: 2

Related Questions