Dynamically bind data with nested properties in js knockout - with dialog (asp.net mvc 3)

I have a table bound to data via Knockout js. Each line has a link to which I hope to show a modal dialog box that will contain input fields that will also be bound to my view model.

This is a server side view model.

public class ViewModel { ...//String getters/setters public IList<SubViewModel> SubViewModels{get;set;} // contains a couple of String properties ... } 

Then I successfully serialize this in the client and bind to the table. Each row of the table has a link:

 <script type="text/html" id="myRowTemplate"> <tr> <td><a href="#" data-bind="click: function(){ myModel.doStuffInADialog($data) }">Do stuff in a popup</a></td> ... other editable text fields, all playing nicely 

This function is called correctly, but I want to pass the current data of the selected row to the template:

 var viewModel = { ... doStuffInADialog: function (selectedRowData) { //how to pass this selectedRowData to the template? d.dialog({ ... jquery dialog stuff }); ... 

this is the template i want to use:

 <script type="text/html" id="nestedPropertyTemplate"> <div class="form-row"> <div> <label>${someFieldOnNestedProperty}</label> </div> <div class="field"> <input data-bind="value: Value"/> </div> <br /> </div> </script> 

and here is the div that I will use for dialogue

 <div data-bind=" template : { name: 'nestedPropertyTemplate', data : SubViewModels() }" style="display: none" class="dialog"> </div> 

So in conclusion. I would like to know if there is a way / better way:

  • Bind a template to a nested property of my JSON object
  • Use the jQuery dialog to display the contents of the div using the template, and put the fields in the dialog box of the dialog into my knockout view model.
  • dynamically enter current row data into a template / dialog
+2
source share
1 answer

If I understood your question correctly, I would add a property of your view model to store the currently selected row, for example:

 myRows: ko.observableArray(....), myCurrentlySelectedRow: ko.observable(null) 

... then in your click handler set the selected line:

 doStuffInADialog: function (selectedRowData) { myCurrentlySelectedRow(selectedRowData); ..... } 

Finally, bind your template to the currently selected line:

 <div data-bind=" template : { name: 'nestedPropertyTemplate', data : viewModel.myCurrentlySelectedRow() }" 

Thus, your template will start and re-display the content whenever your selected line changes your requirement: "dynamically enter the current line data into the template / dialog"

+6
source

All Articles