I'm trying to implement master-slave web page where on the left side is a control on which you can choose an element. On the right side chosen element's details are shown. I'm using asp.net mvc and I've already implemented master control which downloads (using ajax) element's details.
EDIT
Thanks to photo_tom's response and my further research I managed to reload sub-viewmodel and details sub-page. Unfortunately it doesn't work :( If I do something similar to this it works fine. But it fails if I only try to place the inner html dynamically and change the viewmodel afterwards. How to make the bindings work with dynamically replaced element's innerHtml?
@{
ViewBag.Title = "Products";
}
<h2>Products</h2>
<div class="ms-master">
<select size="15" data-bind="
options: Products,
optionsText: 'Name',
value: CurrentProduct
">
</select>
</div>
<div class="ms-slave" data-bind="
with: CurrentProductVM">
<div data-bind="html: $parent.CurrentProductHtml" />
</div>
<script type="text/javascript" language="javascript">
function Product(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
};
function ViewModel(data) {
var self = this;
if (data != undefined) {
ko.mapping.fromJS(data, {
'Products': {
'create': function(d) {
return new Product(d.data);
}
}
}, this);
}
self.CurrentProductHtml = ko.observable();
self.CurrentProductVM = ko.observable();
self.CurrentProduct = ko.observable();
self.OnCurrentProduct = function(value) {
$.getJSON(
self.DetailsUrl(),
{ id: value.Id() },
function (result) {
self.CurrentProductVM(result.Model);
self.CurrentProductHtml(result.View);
}
);
};
self.CurrentProduct.subscribe(self.OnCurrentProduct);
};
$(function () {
var model = @Html.Raw(Json.Encode(Model.Data));
var vm = new ViewModel(model);
ko.applyBindings(vm);
});
</script>
OLD POST
The Details action on the controller returns PartialView on which I want to have a separate KO's viewmodel which controlls the partial view. How to do it? Maybe there's better solutions for my problem?
Here's similar problem but using this solution I'll have to query controller twice: once to get VM, second time to get view, wouldn't I?
JS
function Product(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
self.AsyncDetails = ko.observable();
self.OnSelect = function() {
$.get(
'@Url.Action("Details", "ProductsMgm")',
{ id: self.Id() },
function (e) {
self.AsyncDetails(e);
}
);
};
};
function ViewModel(data) {
var self = this;
if (data != undefined) {
ko.mapping.fromJS(data, {
'Products': {
'create': function(d) {
return new Product(d.data);
}
}
}, this);
}
self.CurrentProduct = ko.observable();
self.OnCurrentProduct = function(value) {
value.OnSelect();
};
self.CurrentProduct.subscribe(self.OnCurrentProduct);
};
** HTML **
<div class="ms-master">
<select size="15" data-bind="
options: Products,
optionsText: 'Name',
value: CurrentProduct
">
</select>
</div>
<div class="ms-slave" data-bind="
with: CurrentProduct">
<div data-bind="html: AsyncDetails" ></div>
</div>