4

How do I build my html inside the razor foreach? I get "Cannot resolve tbody" inside the foreach.

My code:

function loadNyhedsbrevTable() {
    var tbody = "";

    $('#NyhedsbrevTable tbody').empty();
    @foreach (string n in ViewBag.NyhedsbrevListe)
    { 
        tbody = '<tr><td>' + n + '</td></tr>';
    }
    $('#NyhedsbrevTable tbody').append(tbody);
}

Do I need something like this?

<not razor> tbody = '<tr><td>' + @n + <not razor>'</td></tr>';

radbyx
  • 9,352
  • 21
  • 84
  • 127
  • Maybe I can't use foreach and should only use for instead? – radbyx Nov 07 '13 at 10:50
  • Well, it's not exactly HTML, it's javascript. So check here: http://stackoverflow.com/questions/4599169/using-razor-within-javascript For pure HTML see no troubles... – Dmytro Nov 07 '13 at 10:54

2 Answers2

6

Is this what you are looking for? I hope this help

@foreach (string n in ViewBag.NyhedsbrevListe)
{ 
    @:tbody = '<tr><td>' + n + '</td></tr>';
}

Source: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

nico008
  • 111
  • 3
  • This workes too. When I tested it the first time I must have had another error. – radbyx Nov 07 '13 at 11:31
  • I will accept yours instead because you answered first and it's two lines less. It might even be more best pratice, I am not sure. – radbyx Nov 07 '13 at 11:33
2

You cannot mix javascript and razor like that. razor gets processed server side while rendering the page, javascript is a client-side srcipt.

What you would need to do is render a valid piece of javascript code. Assuming you want to append a row for each item in the loop, then something like this should work:

function loadNyhedsbrevTable() {
    var tbody = "";

    $('#NyhedsbrevTable tbody').empty();

    @foreach (string n in ViewBag.NyhedsbrevListe)
    { 
        <text>
            tbody += '<tr><td>@(n)</td></tr>';
        </text>
    }

    $('#NyhedsbrevTable tbody').append(tbody);
}

This would result in the following rendered output, for example:

function loadNyhedsbrevTable() {
    var tbody = "";

    $('#NyhedsbrevTable tbody').empty();

    tbody += '<tr><td>one</td></tr>';
    tbody += '<tr><td>two</td></tr>';
    tbody += '<tr><td>three</td></tr>';

    $('#NyhedsbrevTable tbody').append(tbody);
}
musefan
  • 47,875
  • 21
  • 135
  • 185
  • I am trying the same, where I use to switch back to content mode. I have a error im trying to fix at the moment, but i think it's something else. By the way, don't we need a `@` before the `n`in the loop, so we use the value from razor? – radbyx Nov 07 '13 at 11:02
  • @radbyx: Yes, well spotted. I have updated my answer – musefan Nov 07 '13 at 11:03
  • Ok im testing it now. – radbyx Nov 07 '13 at 11:04
  • 1
    It works wow! I had to change `string` to `var` because the list was IEnumerable, and I had to add `.Text` to `n`, but that was my mistakes. :) – radbyx Nov 07 '13 at 11:11