Search code examples
javascriptasp.net-mvcasp.net-coremodel-view-controllerrazor

MVC JavaScript inside foreach block


The textbox should be filled up with values from the table when the dedicated button is pressed.

@Html.TextBoxFor(model => model.Users, new { @id = "Name" })

... there for I need a button in every line of the table.

@foreach (var user in Model.Users)
{
    <tr>

        <td> <input type="button" value="get" id="btnTakeOver" class="btn btn-primary" /> </td>

        <td>@user.Id</td>
        <td>@user.Name</td>
        <td>@user.Email</td>
    </tr>

}

But I have the problem that the JavaScript doesn't know the variables @user.Name and @user.Email from the foreach block.

The JavaScript block.

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jquery")

    
    <script>
       $(document).ready(function () {

            $("#btnTakeOver").click(function () {
                $("#Name").val(@user.Name);  // val from inside the foreach loop
                $("#Email").val(@user.Email);
            });

        });
        
    </script>
}   

Has anybody an idea how it works?


Solution

  • You can add the data into onclick event of the button:

    <td> <input type="button" value="get" id="btnTakeOver" class="btn btn-primary" onclick="myFunction(@user.Name,@user.Email)" /> </td>
    

    js:

     <script>
          function myFunction(Name,Email){
              $("#Name").val(Name);  // val from inside the foreach loop
              $("#Email").val(Email);
          }
            
        </script>