6

This is the Code I'm having problems with:

@{int i = 1;}
@foreach (var item in Model)
{
    @:<ul id="sortablei" class='droptrue'>
    i++;
}

How can I use i in the id sortablei? I tried: @i or @{i} but it seems without a space before the i its not working. I couldn't find an answer to my problem in the Razor Syntax Reference so I'm a bit clueless right now.

2 Answers 2

11

Brackets:

@:<ul id="sortable@(i)" class='droptrue'>

The brackets here scope the razor expression; in many cases they aren't required, however they are necessary when:

  • the expression (on the right) is non-trivial (spaces. etc) and needs help to scope it
  • where without it, it looks like an email address, i.e. abc@def - this has special handling to avoid breaking pages with email addresses in them
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh so simple, yet it wasn't mentioned in the reference! Thanks a lot!
1

something like this:

@model System.Generic.Collections.List<MyNameSpace.Product>
@{
    int i = 1;
    string sortablei = "abc",
           droptrue = "abc-cls";
}

<ul id="@sortablei" class="@droptrue">
    @foreach (var item in Model)
    {
       <li>@item.Qty x @item.Name</li>
       i++;
    }
</ul>

Here's a quick reference for your knowledge.


Seams like I didn't got it right,

as Mark said, all you need to do is surround the variable with brackets like

sortable@(i)

I hope the reference is somewhat useful, as your particular problem can be found in Explicit Expression example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.