1
votes

I am trying to load a partial view which has a tabstrip. I am making a jQuery ajax call to the controller which returns a partial view which contains the tab strip. I believe all the Telerik JS is being loaded properly.

Here are pieces of the partial view:

        <% Html.Telerik().TabStrip()
        .Name("TabStrip")
        .Items(tabstrip =>
        {
            foreach (FooType foo in Model.Section) {
                tabstrip.Add()
                    .Text(foo.Name.ToString())
                    .Content(() =>
                    {%>
                        <div><%= foo.bar.ToString() %></div>
                    <%});
            }
        })
        .SelectedIndex(0)
        .Render();
         %>

The problem is that has the same content no matter what. Its always the last item from Model.Section. The tab text is is outputted correctly though.

I've tried replacing the foo.bar.ToString with a counter that get incremented at each iteration, but the tabs end up all having the same value, the last counter value.

What am I missing?

1
Any javascript or HTML markup errors? Sometimes, it's because of that.Brian Mains

1 Answers

3
votes

This is a well known problem caused by the lambda capturing the foo variable by reference not by value. When the tabs are rendered the last value of foo will be used. Check this blog post for a more detailed explanation.

The solution is to use a local variable inside the loop:

foreach (FooType foo in Model.Section) {
      var bar = foo.bar.ToString();
      tabstrip.Add()
              .Text(foo.Name.ToString())
              .Content(() => /* use the local variable in the lambda */
               {%>
                   <div><%= bar %></div>
               <%});
}