首页 > 解决方案 > 模态对话框只需单击一个按钮即可加载,而不管类似按钮的数量如何 - 如何修复它?

问题描述

我在视图中创建了一个 Datatables 表,其中包含触发模式对话框的按钮。按钮仅在满足某些条件时出现(确切地说是当图像路径不为空时),并且条件语句在视图内。模态对话框由按钮触发,但只有一个按钮 - 它不会由有条件出现的任何其他按钮触发,尽管它们是由 foreach 语句定位的。为什么对话框不是由不同的按钮触发的,我该如何解决?

这是视图的代码(一些不相关的列没有显示):

@model IEnumerable<WeaponDoc.Models.Item>

@{
    ViewBag.Title = "Index";
    Layout = "~/Areas/Manager/Views/Shared/_LayoutManager.cshtml";
}

<div class="content-wrapper">
    <h2>Объекты</h2>

    <section class="content">
        <table id="itemtable" class="table">
            <thead>
                <tr>

                    <th>
                        @Html.DisplayName("Серийный номер")
                    </th>

                    <th>
                        @Html.DisplayName("Изображение")
                    </th>
                </tr>
            </thead>

            @foreach (var item in Model)
            {
                <tr>

                    <td>
                        @Html.DisplayFor(modelItem => item.ItemSerialNumber)
                    </td>

                    <td>
                        @Html.ActionLink("Загрузить", "Upload", new { itemID = item.ItemID }, htmlAttributes: new { @class = "btn btn-primary", @role = "button" })
                        @{ if (item.ImagePath != null && item.ImagePath.Length > 0)
                            {


                                <p><a href="#myModal2" id="btn2" class="btn btn-success"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>
                                <div id="myModal2" class="modal fade">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                                <h4 class="modal-title">Заголовок модального окна 2</h4>
                                            </div>
                                            <div class="modal-body">
                                                <img src="@Url.Content(item.ImagePath)" alt="@Url.Content(item.ImagePath)">
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
                                                </div>
                                        </div>
                                    </div>
                                </div>
                            }
                            else
                            {
                                Html.Display("Нет изображения");
                            }
                        }
                    </td>

                </tr>
            }

        </table>

    </section>

    @section scripts{

        <link href="~/Content/DataTables/datatables.min.css" rel="stylesheet" />
        <script src="~/Content/DataTables/datatables.min.js"></script>
        <script src="~/Content/DataTables/datatables.js"></script>
        <script src="~/Content/DataTables/Buttons-1.5.2/js/dataTables.buttons.min.js"></script>
        <script src="~/Content/DataTables/Buttons-1.5.2/js/buttons.flash.min.js"></script>
        <script src="~/Content/DataTables/JSZip-2.5.0/jszip.min.js"></script>
        <script src="~/Content/DataTables/pdfmake-0.1.36/pdfmake.min.js"></script>
        <script src="~/Content/DataTables/Buttons-1.5.2/js/buttons.html5.min.js"></script>
        <script src="~/Content/DataTables/Buttons-1.5.2/js/buttons.print.min.js"></script>
        <!-- jQuery -->
        <script src="/examples/vendors/jquery/jquery-3.3.1.min.js"></script>
        <!-- Bootstrap -->
        <script src="/examples/vendors/bootstrap-3.3.7/js/bootstrap.min.js"></script>


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

                $("#itemtable").DataTable(
                    {
                        dom: 'Bfrtip',
                        buttons: [
                            { extend: 'copy', attr: { id: 'allan' } }, 'csv', 'excel', 'pdf', 'print'
                        ],

                        "language":
                        {
                            "processing": "Подождите...",
                            "search": "Поиск:",
                            "lengthMenu": "Показать _MENU_ записей",
                            "info": "Записи с _START_ до _END_ из _TOTAL_ записей",
                            "infoEmpty": "Записи с 0 до 0 из 0 записей",
                            "infoFiltered": "(отфильтровано из _MAX_ записей)",
                            "infoPostFix": "",
                            "loadingRecords": "Загрузка записей...",
                            "zeroRecords": "Записи отсутствуют.",
                            "emptyTable": "В таблице отсутствуют данные",
                            "paginate": {
                                "first": "Первая",
                                "previous": "Предыдущая",
                                "next": "Следующая",
                                "last": "Последняя"
                            },
                            "aria": {
                                "sortAscending": ": активировать для сортировки столбца по возрастанию",
                                "sortDescending": ": активировать для сортировки столбца по убыванию"
                            }
                        }

                    }
                )

                $
            })

        </script>

        <script>
            $(function () {
                $("#btn2").click(function () {
                    $("#myModal2").modal('show');
                });
            });
        </script>
    }
</div>

这是动作的代码:

 public ActionResult Index()
        {
            var items = db.Items.Include(i => i.ItemSubtype);

            return View(items.ToList());

和模型本身:

namespace WeaponDoc.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Item
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Item()
        {
            this.CallDetails = new HashSet<CallDetail>();
            this.OrderDetails = new HashSet<OrderDetail>();
        }

        public System.Guid ItemID { get; set; }
        public string Additional { get; set; }
        public string ItemName { get; set; }
        public string ItemProducer { get; set; }
        public System.Guid ItemSubtypeID { get; set; }
        public string ImagePath { get; set; }
        public System.Guid CalcDetailsID { get; set; }
        public string ItemSerialNumber { get; set; }
        public int Number { get; set; }
        public Nullable<int> ItemStatus { get; set; }

        public virtual CalcDetail CalcDetail { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<CallDetail> CallDetails { get; set; }
        public virtual ItemSubtype ItemSubtype { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<OrderDetail> OrderDetails { get; set; }
    }
}

我知道这段代码中还有很多其他的错误(至少没有加载图片),但首先要做的是——我什至无法让对话框出现。非常感谢您的任何假设。

标签: c#jqueryasp.net-mvcmodal-dialog

解决方案


该元素与导致问题<p><a href="#myModal2" id="btn2" class="btn btn-success"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>的相同元素重复。idId 在页面中应该是唯一的。

您在循环内创建具有元素 id 的相同模式,id="myModal2"这会导致另一个问题。

以下是建议和更新的代码。

使用class名称触发click事件。我已经向show-modal锚元素添加了一个类并从中删除了id。还将图像 src 保留@Url.Content(item.ImagePath)为数据属性

<p><a href="#myModal2" class="btn btn-success show-modal" data-imageurl="@Url.Content(item.ImagePath)"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>

接下来,将模态弹出代码移到循环之外,然后单击锚标记,您可以src使用 jquery 设置图像。

请参阅更新的代码。

     @model IEnumerable<WeaponDoc.Models.Item>

        @{
            ViewBag.Title = "Index";
            Layout = "~/Areas/Manager/Views/Shared/_LayoutManager.cshtml";
        }

        <div class="content-wrapper">
            <h2>Объекты</h2>

            <section class="content">
                <table id="itemtable" class="table">
                    <thead>
                        <tr>

                            <th>
                                @Html.DisplayName("Серийный номер")
                            </th>

                            <th>
                                @Html.DisplayName("Изображение")
                            </th>
                        </tr>
                    </thead>

                    @foreach (var item in Model)
                    {
                        <tr>

                            <td>
                                @Html.DisplayFor(modelItem => item.ItemSerialNumber)
                            </td>

                            <td>
                                @Html.ActionLink("Загрузить", "Upload", new { itemID = item.ItemID }, htmlAttributes: new { @class = "btn btn-primary", @role = "button" })
                                @{ if (item.ImagePath != null && item.ImagePath.Length > 0)
                                    {
                                       <p><a href="#myModal2" class="btn btn-success show-modal" data-imageurl="@Url.Content(item.ImagePath)"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>

                                    }
                                    else
                                    {
                                        Html.Display("Нет изображения");
                                    }
                                }
                            </td>

                        </tr>
                    }

                </table>
       <div id="myModal2" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title">Заголовок модального окна 2</h4>
                </div>
                <div class="modal-body">
                    <img src="" alt="">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
                </div>
            </div>
        </div>
    </div>

            </section>

            @section scripts{

                <link href="~/Content/DataTables/datatables.min.css" rel="stylesheet" />
                <script src="~/Content/DataTables/datatables.min.js"></script>
                <script src="~/Content/DataTables/datatables.js"></script>
                <script src="~/Content/DataTables/Buttons-1.5.2/js/dataTables.buttons.min.js"></script>
                <script src="~/Content/DataTables/Buttons-1.5.2/js/buttons.flash.min.js"></script>
                <script src="~/Content/DataTables/JSZip-2.5.0/jszip.min.js"></script>
                <script src="~/Content/DataTables/pdfmake-0.1.36/pdfmake.min.js"></script>
                <script src="~/Content/DataTables/Buttons-1.5.2/js/buttons.html5.min.js"></script>
                <script src="~/Content/DataTables/Buttons-1.5.2/js/buttons.print.min.js"></script>
                <!-- jQuery -->
                <script src="/examples/vendors/jquery/jquery-3.3.1.min.js"></script>
                <!-- Bootstrap -->
                <script src="/examples/vendors/bootstrap-3.3.7/js/bootstrap.min.js"></script>


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

                        $("#itemtable").DataTable(
                            {
                                dom: 'Bfrtip',
                                buttons: [
                                    { extend: 'copy', attr: { id: 'allan' } }, 'csv', 'excel', 'pdf', 'print'
                                ],

                                "language":
                                {
                                    "processing": "Подождите...",
                                    "search": "Поиск:",
                                    "lengthMenu": "Показать _MENU_ записей",
                                    "info": "Записи с _START_ до _END_ из _TOTAL_ записей",
                                    "infoEmpty": "Записи с 0 до 0 из 0 записей",
                                    "infoFiltered": "(отфильтровано из _MAX_ записей)",
                                    "infoPostFix": "",
                                    "loadingRecords": "Загрузка записей...",
                                    "zeroRecords": "Записи отсутствуют.",
                                    "emptyTable": "В таблице отсутствуют данные",
                                    "paginate": {
                                        "first": "Первая",
                                        "previous": "Предыдущая",
                                        "next": "Следующая",
                                        "last": "Последняя"
                                    },
                                    "aria": {
                                        "sortAscending": ": активировать для сортировки столбца по возрастанию",
                                        "sortDescending": ": активировать для сортировки столбца по убыванию"
                                    }
                                }

                            }
                        )


                    })

                </script>

                <script>
    $(function () {
        $(document).find(".show-modal").click(function () {
            var img_url = $(this).data('imageurl');
            $("#myModal2").find('.modal-body').find('img').attr('src', img_url).attr('alt', img_url);
            $("#myModal2").modal('show');
        });
    });
</script>
            }
        </div>

希望这会有所帮助..


推荐阅读