0

The code in my view -

@{ int tabIndex = 0; }
        @using (var metricGroup = ko.Foreach(m => m.MetricGroups))
        {
            tabIndex++;
            <div id="tabs-@tabIndex" > ... </div>
         }

The issue here is for all the divs rendered, the id is always the same - "tabs-1" instead of that, it should be "tabs-1", "tabs-2", "tabs-3" ...

Can anyone please help me out with this issue? I have a highly complex view and Knockout MVC is driving me crazy

1 Answer 1

1

Because of the ko.Foreach your HTML will be generated on the client side, so setting the your div's id with Razor does not work because the Razor code is executed on server side.

What you need to do is to generate the id's on the client side with Knockout using the $index() binding context property, and the attr binding:

@using (var metricGroup = ko.Foreach(m => m.MetricGroups))
{
    <div data-bind="attr: { id: 'tabs-' + $index() }" > ... </div>
}

The Knockout-Mvc's ko.Bind.Attr method is not working with the GetIndex() method so you need to write out the this Knockout binding expression by hand.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. I tried this earlier but i am facing one issue. This code generates the Ids but since we are using index, they look like id=0, id=1, id=2 .... I tried using <div data-bind="attr: { id: 'tabs-' + $index() + 1 }" > ... </div> But that didnt work either. What i want is ids should start from 1,2,3...
You just need to correctly group the expression: <div data-bind="attr: { id: 'tabs-' + ( $index() + 1 ) }" > note the ( ) jsfiddle.net/S8KQP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.