Razor syntax inside attributes of html elements (ASP MVC 3)

asp.net MvcRazorasp.net Mvc-3

asp.net Mvc Problem Overview


I have a table with repeating customer rows, I would like to add the customer ID to the ID attribute of my table rows like this:

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

I try adding this code:

@foreach(var c in Model) {
   <tr id="[email protected]"></tr>
}

Which gives me the following output:

<tr id="[email protected]"></tr>
<tr id="[email protected]"></tr>

etc.

But I would like it to be:

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

etc.

I also tried to add <tr>row@{c.id}</tr> but it did not work..

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

The actual reason why this doesn't work is because your [email protected] matches the regex for an email address. So the parser assumes it's an email and not actually an attempt to call code. The reason row@{c.id} doesn't work is because the @{} doesn't output and is meant to contain blocks of code.

When in doubt you should use @() as it will force what's contained between the () to be parsed as code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin at MenntView Question on Stackoverflow
Solution 1 - asp.net MvcBuildstartedView Answer on Stackoverflow