Reputation: 448
I have a image control and file input control,
<img data-bind="attr:{src:Picture}">
<span><i class="fa fa-edit"></i></span><input type="file" name="Picturefile" data-bind="value: Picture"></label>
<div class="btn btn-group">
<button type="submit" value="save" data-bind="click: editClient" class="btn btn-primary"><i class="fa fa-ok"></i>Save!</button>
<a href="/admin/client" class="btn btn-info"><i class="fa fa-arrow-left"></i>Back to list</a>
</div>
On editing a entity, I want to bind the current picture with image control, also the user can edit and select a new picture using file control,
Here is my javascript,
<script type="text/javascript">
$(function () {
var ClientObject = {
Name: "",
Picture: ""
}
function Client(data) {
var self = this;
this.editClient = function () {
var datatoPost = ko.mapping.toJS(self);
$.ajax({
async: false,
method: 'post',
type: 'application/json',
url: '/api/my/client/',
data: datatoPost,
success: function (d) {
toastr.info("Saved");
}
})
}
console.log('mapping to js',data);
ko.mapping.fromJS(data, ClientObject, self);
}
var loadData = function (id) {
var _url = '/api/v2/my/client';
$.ajax({
type: 'get',
url: _url + '/' + id,
success: function (d) {
if (!!d.error) { console.log(d.message); }
else {
var model = new Client(d);
ko.applyBindings(model, document.getElementById("clientCreate"));
console.log(model);
}
}
});
}
loadData(@ViewBag.Id);
});
</script>
So on loading I get the following error:
Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
New to knockout !!
Upvotes: 0
Views: 4043
Reputation: 7958
I had to create a custom binding to do it. I haven't done any cross browser testing but I think it will work on all current browsers.
<input type="file" data-bind="fileSrc: src" id="file"/>
<img data-bind="attr:{src:src}"/>
$(function() {
ko.applyBindings(new ViewModel());
});
var ViewModel = function () {
var self = this;
self.src = ko.observable();
};
ko.bindingHandlers.fileSrc = {
init: function (element, valueAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
var reader = new FileReader();
reader.onload = function (e) {
var value = valueAccessor();
value(e.target.result);
}
reader.readAsDataURL(element.files[0]);
});
}
};
Upvotes: 3