Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..

like image 499
Martin at Mennt Avatar asked Sep 12 '10 18:09

Martin at Mennt


People also ask

What is Razor syntax in ASP.NET MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML.

What is Razor syntax?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.

What is Razor in MVC What are the main Razor syntax rules?

Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.

What are the main Razor syntax rules?

Razor code blocks are enclosed in @{ … } Inline expressions (variables and functions) start with @ Code statements end with a semicolon. Variables are declared with the var keyword.


1 Answers

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.

like image 77
Buildstarted Avatar answered Sep 21 '22 08:09

Buildstarted