I am currently working on integrating an MVC ListBoxFor control with a Kendo MultiSelectFor to bind and update data.
The goal is to have a list of users in the ListBox, and a list of available users in the MultiSelect box. When users are selected from the MultiSelect box and the add button is clicked, an Ajax call is made to update the users list server-side. The client-side JavaScript then updates the users and available users array object, keeping the controls up-to-date with the updated lists.
While I wish there was just one issue to tackle, each attempt seems to bring about different errors. So, let's focus on the latest problem:
Model:
public IEnumerable<UserInformation> Users { get; set; }
public IEnumerable<UserInformation> AvailableUsers { get; set; }
JavaScript ViewModel:
var viewModel = kendo.observable({
availableUsersSelected: [],
users: @(Html.Raw(Json.Encode(this.Model.Users))),
availableUsers: @(Html.Raw(JsonConvert.SerializeObject(this.Model.AvailableUsers))),
moveToUsers: function () {
this.availableUsersSelected = this.get('availableUsersSelected');
this.users.push(this.availableUsers);
if (this.availableUsersSelected.length > 0) {
var formAction = '@Url.Combine(Url.Content("~/"), ControllerActions.Groups.GroupDefault, ControllerActions.Groups.AddUser)';
$.ajax({
url: formAction,
type: 'POST',
data: {
model: JSON.stringify(
{
groupId: $('#GroupId').val(),
users: this.availableUsersSelected
}
)
},
success: function (result) {
if (result) {
this.users.remove(this.availableUsersSelected);
}
}
});
}
}
});
MultiSelectFor control
@(Html.Kendo()
.MultiSelectFor(u => u.AvailableUsers)
.Placeholder("Please select")
.BindTo(new SelectList(Model.AvailableUsers, "Id", "Name"))
.HtmlAttributes(new { data_bind = "value: availableUsersSelected" })
)
ListBox control
@(Html.EditorLine(Language.Fields.Users, Html.ListBoxFor(u => u.Users, new SelectList(Model.Users, "Id", "Name"), new { @class = "form-control", data_bind = "source: users", data_value_field ="Id", data_text_field = "Name" })))
Add control
<img src="~/Content/images/up-arrow.jpg" alt="Move to users" width="30" data-bind="events: {click: moveToUsers}" />
In summary, while the Ajax calls and server-side updates are successful, I am encountering challenges with the client-side control binding.
The specific errors I'm facing include a syntax error with the comma on this line
users: @(Html.Raw(Json.Encode(this.Model.Users))),
, as well as a "ReferenceError: Id is not defined" when the moveToUsers function is called upon clicking the add button.
(Apologies for any frustration coming through in the question - this process has been quite challenging.)