Reputation: 9670
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>'
;
Upvotes: 4
Views: 5481
Reputation: 48425
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);
}
Upvotes: 2
Reputation: 111
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
Upvotes: 6