Home > OS >  MVC JavaScript inside foreach block
MVC JavaScript inside foreach block

Time:01-19

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"  /> </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?

CodePudding user response:

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

<td> <input type="button" value="get" id="btnTakeOver"  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>
  • Related