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

tereško
  • 58,060
  • 25
  • 98
  • 150
user979189
  • 1,230
  • 2
  • 15
  • 39

1 Answers1

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
  • 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
    ...
    But that didnt work either. What i want is ids should start from 1,2,3...
    – user979189 Dec 26 '13 at 15:10
  • You just need to correctly group the expression: `
    ` note the `( )` http://jsfiddle.net/S8KQP/
    – nemesv Dec 26 '13 at 15:58