Knockout MVC with existing C# code - looping

泪湿孤枕 提交于 2019-12-08 11:52:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!