I am trying to add dynamic id
to div
inside a foreach
loop concatenated with value of variable i
. It throws syntax errors. What might be the issue. Can we achieve this solution without using a for
loop ?
@{int i=1;}
@foreach (var or in Model.Names)
{
<div oid="@or.Id" mode="0" oids="@or.Id" id="tr"+i>
@or.Name
</div>
i++;
}
for myself, none of this solutions worked but adding my @i first did work,
id="@i+AnyText"
after building it, and inspecting ill getid="1+AnyText"
, for the next oneid="2+AnyText"
and so on (im using 2013vs)..hope that helps anyone, have a nice day.
You can't append like this:
It must be:
You need the
@
.. since it won't be able to deduce between markup and Razor at that point.in the newly C# 6 you can directly use id="@($"tr{i}")"
You want to construct ID in C# segment of code. One option is to do whole construction with string format:
Or
id="@("tr"+i)"
orid="tr@(i)"
Note that you can't do just
id="tr@i"
because the Razor syntax parser ignores "text@text" as it looks like a normal email address.