ASP.NET MVC Razor Concatenation

asp.net Mvcasp.net Mvc-3Razorasp.net Mvc-4

asp.net Mvc Problem Overview


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.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

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

Solution 2 - asp.net Mvc

How about using String.Format? like this:

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

Solution 3 - asp.net Mvc

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.

Solution 4 - asp.net Mvc

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.

Solution 5 - asp.net Mvc

You can so this in a simpler way:

id="[email protected]"

Solution 6 - asp.net Mvc

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

id="[email protected]"

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
QuestionDavid MarchelyaView Question on Stackoverflow
Solution 1 - asp.net MvcMatthew AbbottView Answer on Stackoverflow
Solution 2 - asp.net MvcFilip EkbergView Answer on Stackoverflow
Solution 3 - asp.net MvcGary WoodfineView Answer on Stackoverflow
Solution 4 - asp.net MvcShaiju TView Answer on Stackoverflow
Solution 5 - asp.net Mvcanil shresthaView Answer on Stackoverflow
Solution 6 - asp.net Mvcuser13705409View Answer on Stackoverflow