Search code examples
asp.netknockout.jsmarkup

Combine code with info from databound item in ASP.NET markup code blocks


Man, I never really learnt all the embedded code blocks and stuff you can use in ASP.NET. What I'm trying to do is the following:

  • I have a repeater
  • It renders a table
  • In each row, I need to add a data-bind attribute (yes, for Knockout) containing some text and the rowindex.

More specifically, I want to render:

<table>
    <tr data-bind="with:myItems()[0]">
        ...
    </tr>
    <tr data-bind="with:myItems()[1]">
        ...
    </tr>
    <tr data-bind="with:myItems()[2]">
        ...
    </tr>
</table>

I've tried:

data-bind="<%# String.Format("myItems()[{0}]", Container.ItemIndex) %>"

But that doesn't work (data-bind="<%# Container.ItemIndex %> will however. So I'm trying to combine code with information from the databound item.

I know there is a foreach binding in Knockout, but I can't use it because:

  • I want/need my HTML to be constructed server-side initially
  • There's other, specific javascript that needs the HTML to exist already so I can't let Knockout populate the table
  • I'm using an ASP.NET Repeater, which doesn't mix well with Knockout's templates.

I also know, I could just do this in code-behind (with <tr runat="server" ... >) but I'm trying to put all my layout and javascript in markup and js files, not in C# code.

So, can I, in some way, add code in my markup to combine text I choose, with info from the current databound item?


Solution

  • Bummer, apparently, the answer is dead simple, and it didn't work the first time because of another mistake I made:

    <tr data-bind="with: myItems()[<%# Container.ItemIndex %>]">
    

    I put more info on my Blog and a working example on GitHub.