inlines
inlines

Reputation: 105

knockout radio group inside foreach binding works one way only

Im using Knockout JavaScript library v2.2.0rc.

I wonder, whether it is possible to do the following.

my template looks like this

<script type="text/html" id="@Html.UniqueId("WorkflowRulesDisplay_template")">
<div data-bind ="foreach: items">
    <fieldset>
        <legend>
            <span data-bind="text: StName"/>
        </legend>
        <dl class="row">
            <dt class="label">
                <label>Member Type:</label>
            </dt>
            <dd class="field">
                <div><input type="radio" value = "User" data-bind="attr :{name:'@Html.UniqueId("wf_usr_radio_grp_")' + StId, checked: CheckedUsr}"/>User</div>
                <div><input type="radio" value = "Group" data-bind="attr :{name:'@Html.UniqueId("wf_usr_radio_grp_")' + StId, checked: CheckedGrp}" />Group</div>
            </dd>
        </dl>
        <dl class="row">
            <dt class="label">
                <label>Description:</label>
            </dt>
            <dd class="field">
                <textarea rows ="5" cols="20" class ="textbox simple-text" data-bind="value: Description"></textarea>
            </dd>
        </dl>
    </fieldset>
</div>

My viewmodel and init code looks like this:

this._items = ko.observableArray(workflow.data('workflow_list_data'));
var viewModel = { items: this._items};
ko.applyBindingsToNode(this._containerElem.get(0), { template: { name:workflow.attr('id').replace('_workflow_control', '_template') } }, viewModel);

where workflow.data('workflow_list_data') is

data.Select(x => new { StName = x.StatusType != null ? x.StatusType.Name : string.Empty, StId = x.SuccessorStatusId, CheckedGrp = !x.GroupId.HasValue, CheckedUsr = !x.UserId.HasValue, x.UserId, x.GroupId, x.Description });

, so client-side, I have this: [Object{StName="lala", StId=123, CheckedGrp=false, CheckedUsr=true, Description="lala"}....{...}]

It all goes fine, but the radio group. Changing the selected button never changes the viewmodel. Ive tried checked and attr-value binding - all the same.

Upvotes: 0

Views: 807

Answers (1)

Alex
Alex

Reputation: 38529

The problem is that CheckedUsr and CheckedGroup aren't observables.
Instead of

this._items = ko.observableArray(workflow.data('workflow_list_data'));

try

this._items = ko.mapping.fromJS(workflow.data);
// not sure what worflow.data is at this point?

This should create an observableArray from your data, with the properties set to ko.observable

Upvotes: 0

Related Questions