Kurkula
Kurkula

Reputation: 6762

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++;
}

Upvotes: 28

Views: 61530

Answers (5)

atamata
atamata

Reputation: 1077

After struggling with this for a while I found that id="@("tr"+i)" did the job for me

Upvotes: 1

misterzik
misterzik

Reputation: 1870

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.

Upvotes: 1

Cătălin Rădoi
Cătălin Rădoi

Reputation: 1894

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

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

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.

Upvotes: 59

Simon Whitehead
Simon Whitehead

Reputation: 65059

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.

Upvotes: 4

Related Questions