0

This is a part of my .cshtml code:

<div class="mclass">
    <div class="MHeader">@s.Name</div>
    @foreach (var sc in @s.items)
        {
        <div class="itemclass" id="{'Item_'[email protected]()}">@sc.itemId</div>
        }
</div>

I want to generate dynamic id for itemclass objects with this furmula: id = 'Item_'+ Id (Id of item).

I used above method but not answer correctly.

1
  • What does this have to do with jQuery? That's server-side MVC code... Commented May 29, 2015 at 13:44

3 Answers 3

2
<div class="itemclass" id="[email protected]()">@sc.itemId</div>
Sign up to request clarification or add additional context in comments.

Comments

0

You need something like this:

public static class MyCounter {

   private static int _uniqueID = 0;

   public static int GetCounter(){
      _uniqueID ++;
      return _uniqueID ;
    }
 }

and then in your cshtml file:

<div class="itemclass" id="{'Item_'+@GetCounter()}">@sc.itemId</div>

Comments

0

If you change your foreach to a for, you can use the counter:

<div class="mclass">
    <div class="MHeader">@s.Name</div>
    @for(var i = 0; i < s.items.Count; i++)
        {
            <div class="itemclass" id="Item_@(i+1)">
                @s.items[i].itemId
            </div>
        }
</div>

The above assumes a 1 based counter on the id.

If you want to bind the collection i.e. send it back to the server you will need to understand how the model binding works.

Model Binding To A List Article

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.