Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc razor foreach loop adding id to div

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++;
}
like image 808
Kurkula Avatar asked Jan 24 '14 01:01

Kurkula


4 Answers

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.

like image 150
Alexei Levenkov Avatar answered Nov 01 '22 12:11

Alexei Levenkov


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.

like image 28
Simon Whitehead Avatar answered Nov 01 '22 13:11

Simon Whitehead


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

like image 3
Cătălin Rădoi Avatar answered Nov 01 '22 13:11

Cătălin Rădoi


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.

like image 1
misterzik Avatar answered Nov 01 '22 13:11

misterzik