Akbari
Akbari

Reputation: 2409

Model binding fails with Kendo MultiSelect

In the model I have long? field that I like to use Kendo MultiSelect for it. The main reason for this choice is server-side filtering. It doesn't reflect current Model's value, nor it sends any value to the server. By inspected traffic, I'm sure that it doesn't update the model's value.

@(Html.Kendo().MultiSelectFor(x => x.theField)
    .Name("msname")
    .MaxSelectedItems(1)
    .Placeholder("")
    .HighlightFirst(true)
    .DataValueField("Id")
    .DataTextField("Text")
    .AutoBind(true)
    .DataSource(ds =>
        ds.Read(" ", "API").ServerFiltering(true))
    .Value(new long?[] { Model.theField})
)

I can put a hidden field and update its value or multiselect's change, but there should be a better solution.

I should note that this multi select is in an editor template and is used by Kendo Grid in popup editor.

UPDATE

When using nullable types, you need to use ValuePrimitive(true)! So the end code is:

@(Html.Kendo().MultiSelectFor(x => x.theField)
    .MaxSelectedItems(1)
    .Placeholder("")
    .HighlightFirst(true)
    .DataValueField("Id")
    .DataTextField("Text")
    .AutoBind(true)
    .DataSource(ds =>
        ds.Read(" ", "API").ServerFiltering(true))
    .ValuePrimitive(true)
)

Upvotes: 3

Views: 3108

Answers (1)

Dion D.
Dion D.

Reputation: 2596

The main reason for this choice is server-side filtering

You can find on their demo site that DropDownList and ComboBox also support that feature. But if you insist to use MultiSelect then lets dig some of your code.

Look Name() method will give a name for your input element e.g (input, select). When form serialized it will use our input name as form's field property. If you are using HtmlHelper that ends with "For" e.g (LabelFor, MultiSelectFor) input attribute name will be named by its binded property.

Html.Kendo().MultiSelectFor(x => x.theField)

You will have

<select name="theField"> ....

You don't have to use Name() method anymore, therefore MultiSelect value will be binded as theField property as per form serialized to server.

Now if you look to Request.Form["theField"] when you debug inside your controller, you will see what value being sent. It usually a content of joined string array if multiple items selected, so you need to change theField type to handle array of string or int instead of nullable long type.

EDIT

At last you find the way to solve your problem, this solution credit to Akbari

When using nullable types, you need to use .ValuePrimitive(true)

Upvotes: 3

Related Questions