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++;
}
You want to construct ID in C# segment of code. One option is to do whole construction with string format:
<div oid="@or.Id" mode="0" oids="@or.Id" id="@string.Format("tr{0}",i)">
Or id="@("tr"+i)"
or id="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.
You can't append like this:
id="tr"+i>
It must be:
id="tr@i">
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}")"
for myself, none of this solutions worked but adding my @i first did work, id="@i+AnyText"
after building it, and inspecting ill get id="1+AnyText"
, for the
next one id="2+AnyText"
and so on (im using 2013vs)..
hope that helps anyone, have a nice day.