问题
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:
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.
来源:https://stackoverflow.com/questions/20764763/knockout-mvc-with-existing-c-sharp-code-looping