Q:

How to duplicate JavaScript inside the for loop

Consider the following code:
<body>
    @for (int i = 0; i < Model.Count(); i++)
    {

        @Html.TextBoxFor(model => Model[i].Name)
        @Html.ValidationMessageFor(model => Model[i].Name)

        <button id="open" onclick="activate()" class="btn btn-default">Open</button>
        <div id="box" style="display: none">
            Hi @Html.TextBoxFor(model => Model[i].Name)
        </div>

    }
    <script type="text/javascript">
        function activate() {
            $('#box').show();

        }

    </script>
</body>

As you can see from my code above, when an user click "Open", the div with ID "box" will be shown, however, what I want is to show multiple div id Box, depends on the For-loop. At the moment, the button can be generated successfully, but there's only one box because both refer to the same ID "box". Is it possible to duplicate or add index into the id="box", so the number of box will be depends on the for loop?

A:

While duplicating the JS is one way of achieving this it's not very DRY. Given your current code you will also encounter problems using duplicate id attributes as they must be unique within the DOM.
A better solution would be to instead genericise the HTML and JS such that one single event handler will work for all instances of that HTML structure. 
To do that you can use class attributes to group your HTML elements and select them in jQuery. Something like this:
$(function() {
  $('.open').click(function() {
    $(this).next('.box').show();
  });
});

.box { display: none; }

@foreach (var item in Model)
{
  @Html.TextBoxFor(model => item.Name)
  @Html.ValidationMessageFor(model => item.Name)

  <button type="button" class="btn btn-default open">Open</button>
  <div class="box">
    Hi @Html.TextBoxFor(model => item.Name)
  </div>
}

Note that you're using an editable textbox for the greeting; presumably that should just be Hi @item.Name

