简体   繁体   中英

Get id in bootstrap modal when button click on same page

I have multiple buttons to invoke a bootstrap model in a page the buttons are generated through foreach loop based on db table rows example if db table has two rows the first row id is 1, and second row id is 2 that's mean tow buttons are generated and I have set specific id to each button and i want when user click on button the bootstrap popup modal will open and display the button id in modal which one the clicked.

I want to pas button holded id to modal within the same page

You could refer to the following demo

View code

@model IEnumerable<MVC2_1Test.Models.City>

@{
ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CityName)
        </th>
        <th>

        </th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CityName)
            </td>
            <td>
                <button data-id="@item.Id" data-toggle="modal" data-target="#myModal" class="ModalClick"> Edit </button>
            </td>
        </tr>
    }
</tbody>

Modal code , <input type="text" name="id" id="id" /> in the modal-body to get the id of button

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">Details</h4>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label class="control-label">Id:</label>
                <input type="text" name="id" id="id" />
            </div>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

In jQuery , get the specific id of each button through data-id="@item.Id" , and set the id to the <input type="text" name="id" id="id"/> in the modal-body.

  @section Scripts
{
<script type="text/javascript">
    $(".btnModal").click(function () {
        var passedID = $(this).data('id');//get the id of the selected button
        $('input:text').val(passedID);//set the id to the input on the modal
    });
</script>

How it works

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM