I have the following simpified ViewModel in C#
public class SearchViewModel
{
public IList<IdAndNameModel> AvailableTags { get; set; }
public IList<IdAndNameModel> SearchTags { get; set; }
}
and this in JavaScript:
function ViewModel() {
var self = this;
self.allTags = ko.observableArray();
self.searchTags = ko.observableArray();
// stuff to fill the searchTags
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.allTags(@Html.Raw(Json.Encode(@Model.AvailableTags)));
Now I want to bind the JavaScript property to the SearchModel:
@Html.HiddenFor(m => m.SearchTags, new { data_bind = "value: searchTags" })
Here is the snippet how the data is submitted to the controller:
$('#submitButton').click(function () {
var form = $('#criteriaForm');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function (result) {
// unimportant binding stuff
}
});
});
Unfortunately the length of the list is always 0. I bet the reason is the initialisation of the availabaleTags array (@Html.Raw(Json.Encode(@Model.AvailableTags))). I am right? If I change the type from list to string then I can see that the binding is generally working.
Is there a way to bind lists in that way?
data: form.serialize()form.serialize()is your problem because it is not correctly serializes your array in the form how ASP.NET would accept it. Please post your ajax code! By the way if you have your viewmodel bacause of KO why don't you send the data from that directly in your ajax call?