Razor syntax inside html element attributes (ASP MVC 3)

I have a table with repeating rows of clients, I would like to add a client identifier to the ID attribute of my table rows as follows:

<tr id="row<customer id>"></tr> 

I am trying to add this code:

 @foreach(var c in Model) { <tr id="row@c.id"></tr> } 

Which gives me the following result:

 <tr id="row@c.id"></tr> <tr id="row@c.id"></tr> 

and etc.

But I would like to:

 <tr id="row1"></tr> <tr id="row2"></tr> 

and etc.

I also tried adding <tr>row@{c.id}</tr> , but that didn't work.

+60
asp.net-mvc asp.net-mvc-3 razor
Sep 12 2018-10-18
source share
1 answer

Have you tried <tr>row@(c.id)</tr> ?

The actual reason this doesn't work is because your row@c.id matches the regular expression for the email address. Thus, the parser accepts this email, and not an attempt to call the code. The reason row@{c.id} does not work because @{} does not output and must contain blocks of code.

If in doubt, you should use @() , as it will force what is contained between () be treated as code.

+104
Sep 12 '10 at 19:34
source share



All Articles