I found this, but this doesn't work for me: Bind to simple array of strings
I am just trying to manage an array of strings through knockout. Here is my markup:
<div class="editor-field">
<table>
<thead>
<tr>
<th>Page Urls</th>
<th></th>
</tr>
</thead>
<!-- ko if: RouteUrls().length > 0 -->
<tbody data-bind="foreach: RouteUrls">
<tr>
<td><span data-bind="text: $data"></span></td>
<td><a href="#" class="ui-icon ui-icon-closethick" data-bind="click: $root.removeUrl">Remove</a></td>
</tr>
</tbody>
<!-- /ko -->
<!-- ko if: RouteUrls().length < 1 -->
<tbody>
<tr>
<td colspan="3"> No urls added for editing.</td>
</tr>
</tbody>
<!-- /ko -->
</table>
@Html.HiddenFor(x => x.UrlCount, new { data_bind = "value:RouteUrls().length" })
@Html.ValidationMessageFor(x => x.UrlCount)
</div>
And here is my knockout code:
<script type="text/javascript">
var mappedModel = ko.mapping.fromJS(@Html.Raw(JsonConvert.SerializeObject(Model)));
mappedModel.RouteUrls = ko.observableArray([]);
mappedModel.urlToAdd = ko.observable("/");
mappedModel.addUrl = function() {
var duplicateValues = ko.utils.arrayFilter(this.RouteUrls(), function (item) {
return item == mappedModel.urlToAdd();
});
if ((this.urlToAdd() != "") && (duplicateValues.length == 0)) // Prevent blanks and duplicates
{
this.RouteUrls().push(this.urlToAdd());
this.urlToAdd("/");
console.log(this.RouteUrls().length);
console.log(this.RouteUrls());
}
};
mappedModel.removeUrl = function(url) {
mappedModel.RouteUrls.remove(url);
};
//other code...
ko.applyBindings(mappedModel);
$.validator.unobtrusive.parse("#pageCForm");
$("#pageForm").data("validator").settings.submitHandler = mappedModel.save;
</script>
Now the problem is, in my markup, the collection never shows. When I try and add a url, even if I remove the knockout if conditional and just display the table, it is always empty. If I try and submit the page, I have unobtrusive validation running on the hidden field for URL count and it acts like it's empty too. So everything in the markup is acting like RouteUrls()
is always empty. But when I log the RouteUrls().length and text to the console I get the following after successive attempts to add:
1
["/sdfsd"]
2
["/sdfsd", "/trgfd"]
3
["/sdfsd", "/trgfd", "/fdfdggdbjn"]
So I don't understand how in the script code the length and array are properly getting populated, but it's not being reflected in the markup. Any help?