Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Razor Concatenation

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="[email protected]">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.

like image 799
David Marchelya Avatar asked Jan 16 '11 00:01

David Marchelya


Video Answer


2 Answers

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

<li id="item_@(item.TheItemId)"> 
like image 183
Matthew Abbott Avatar answered Sep 19 '22 12:09

Matthew Abbott


How about using String.Format? like this:

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

like image 32
Filip Ekberg Avatar answered Sep 23 '22 12:09

Filip Ekberg