Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding with multiple PartialViews in Knockout

enter image description here

I've got a jQuery Accordion and each panel contains a form. All of the forms are the same, and the inputs share the same IDs, names, and data-bind attributes.

Assuming each form has a different binding context (using ko with:), this is how I would set up the Knockout.js ViewModel if there were two forms.

However, I don't know in advance how many forms there will be. I'm rendering a PartialView (which contains the form) for every form object in the MVC ViewModel's collection of forms.

@model ViewModel

<div class="container-fluid">
    <div id="jQueryAccordion">

        @foreach (var form in Model.AllForms.ToList())
        {
           <!-- ko with: items[@form.Key] -->
           Html.RenderPartial("_Form", form);
           <!-- /ko --> 
        }

        // etc.

How would I set up the Knockout.js ViewModel if I don't know how many forms there are going to be?

like image 995
alex Avatar asked Dec 30 '25 04:12

alex


1 Answers

I suggest that you can load your partial view dinamically via ajax call & bind data knockout binding accordingly as follows:

//C# XxxController: return partial view:
public ActionResult MyView()
{
    return PartialView("_MyView");
}

//Ajax call to load partial view at client side:
$.get('Xxx/MyView', function(view){
    _contentHolder.html(view);
    ko.applyBinding(self, _contentHolder[0]);
})

You can loop through your model collection and apply knockout binding dynamically.

like image 200
Anh Bui Avatar answered Jan 01 '26 20:01

Anh Bui