102

I'm trying the render an HTML list that looks like the following, using the Razor view engine:

<ul>
  <li id="item_1">Item 1</li>
  <li id="item_2">Item 2</li>
</ul>

The code that I am attempting to use to render this list is:

<ul>
@foreach (var item in Model.TheItems)
{            
  <li id="item_@item.TheItemId">Item @item.TheItemId</li>
}
</ul>

The parser is choking, because it thinks that that everything to the right of the underscore in the id attribute is plain text and should not be parsed. I'm uncertain of how to instruct the parser to render TheItemId.

I don't want to but a property on the model object that includes the item_ prefix.

I also have to keep this syntax as I am using the list with JQuery Sortable and with the serialize function that requires the id attribute to be formatted in this syntax.

David Marchelya
  • 3,352
  • 4
  • 21
  • 24

6 Answers6

218

You should wrap the inner part of the call with ( ):

<li id="item_@(item.TheItemId)">
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • 3
    I started with String.Format but prefer the syntax and brevity of your response, I'm marking it as my preferred answer. – David Marchelya Jan 16 '11 at 00:31
  • I'm using Visual Studio 2013 and ASP.NET MVC 5, and this is not working (the string is set *as is*, including the `@` and the parentheses)... What finally worked for me was the very ungraceful `id="foo" + Model.Bar`. – Ian Campbell Jan 05 '14 at 05:46
  • This gave me the variable in parenthesis. It appears that Razor now understands that an underscore + a variable = a string + a variable. – Hugh Seagraves Nov 05 '19 at 20:10
27

How about using String.Format? like this:

<li id="@String.Format("item_{0}", item.TheItemId)">

Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
  • This is not parsing correctly, due to nested double-quotes... should the inner quotes be single-quotes and the outer double-quotes, something like `id="@String.Format('foo{0}', item.Bar)"`? – Ian Campbell Jan 05 '14 at 05:48
12

I prefer:

<li id="@String.Concat("item_", item.TheItemId)">

The verbosity tells the support developers exactly what is happening, so it's clear and easy to understand.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Gary Woodfine
  • 387
  • 3
  • 12
2

You can even use this way to concat more strings:

<li id="@("item-"+item.Order + "item_"+item.ShopID)" class="ui-state-default"></li>

Here is another post.

Hope helps someone.

Community
  • 1
  • 1
Shaiju T
  • 6,201
  • 20
  • 104
  • 196
0

You can so this in a simpler way:

id="item_@item.TheItemId"
anil shrestha
  • 2,136
  • 2
  • 12
  • 26
0

This post seems to be older but now this does works now in latest MVC:

id="item_@item.TheItemId"