asp.net mvc razor foreach loop adding id to div

in the newly C# 6 you can directly use id="@($"tr{i}")"


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.


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.


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.