1

I am trying to do the following:

@foreach(var p in @Model.line_products){
<img class="small_img_@Model.line_products[i].short_name" src="/Content/images/@Model.line_products[i].image_name" />
}

Which isn't working, it renders the text just the way it is, not recognizing the '@'. I found this other post in Stackoverflow, which suggests adding parenthesis in the following way:

@foreach(var p in @Model.line_products){
<img class="small_img_(@Model.line_products[i].short_name)" src="/Content/images/@Model.line_products[i].image_name" />
}

Using this workaround, I get that my id is rendered as small_img_(MODEL ATTRIBUTE). Isn't there a workaround which doesn't require adding specific characters? (such as the parenthesis).

Community
  • 1
  • 1
Soph
  • 2,895
  • 5
  • 37
  • 68
  • 1
    Out of curiosity, are you sure you want to be using an index in a foreach loop? Should your markup be `small_img_@(p.short_name)` instead? – Brandon Oct 31 '12 at 21:15
  • Context please? Which text rendered the way it is? What comes before this markup? – Jonathan Wood Oct 31 '12 at 21:15
  • I am using the index for html purposes, and so I forgot to use the p variable declared in the foreach. When the 'i' variable reaches certain values I open/close tags. You were right! It was as simple as placing the '@' outside. Silly mistake, thanks so much! – Soph Oct 31 '12 at 21:22

3 Answers3

4

You have more errors than a simple undercore problem here. You cannot use @Model inside your if. You are already in a @ block. Simply use @foreach(var p in Model.line_products).

Plus, the way you wrote the parenthesis, they will get rendered. What you want is

small_img_@(Model.line_products[i].short_name)
Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101
2

Put the parenthesis after the @ instead of before:

class="small_img_@(Model.line_products[i].short_name)"
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

I sometimes put a couple of Guids in the id of an element and an underscore separator doesn't work.

There are two ways around this. First use the entity code &#95; instead and secondly just use a hyphen.

 <input id="chk_@classLeader.ClassLeader&#95;@ing.Ingredient.Guid" type="checkbox" class="chk_Done form-check">

 <input id="chk-@classLeader.ClassLeader-@ing.Ingredient.Guid" type="checkbox" class="chk_Done form-check">

This is because I want to grab out the Guid's when the check box is clicked with some JQuery like this:

$(".chk_Done").click(function () {

    var obj =[];

    const itemId = ($(this).attr("id"));
    const myArray = itemId.split("_");
    var ClassLeaderGuid = myArray[1], IngredientGuid = myArray[2];
Norbert Norbertson
  • 2,102
  • 1
  • 16
  • 28