简体   繁体   English

模态对话框仅通过单击一个按钮即可加载,而不管类似按钮的数量如何-如何解决?

[英]Modal dialog loads just from the click on one button regardless of the number of similar buttons - how to fix it?

I create a Datatables table inside a view with buttons that trigger modal dialog. 我在一个视图内创建一个带有触发模式对话框的按钮的Datatables表。 The buttons appear only when some condition is met (exactly when image path is not null), and conditional statement is inside the view. 仅当满足某些条件时(确切地说,当图像路径不为null时),并且条件语句位于视图中时,按钮才会出现。 Modal dialog is triggered by the button, but just one button - it is not triggered by any other buttons that conditionally appear, although they are positioned by foreach statement. 模态对话框由按钮触发,但仅由一个按钮触发-尽管有条件的对话框是由foreach语句定位的,但它不会由有条件出现的任何其他按钮触发。 Why isn't the dialog triggered by different buttons and how can I fix it? 为什么对话框不是由不同的按钮触发的,我该如何解决?

That's the code of the view (some irrelevant columns are not shown): 这就是视图的代码(一些不相关的列未显示):

@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>

Here's the code of the action: 这是动作的代码:

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

            return View(items.ToList());

And the model itself: 和模型本身:

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; }
    }
}

I know that there's a ton of other bugs in this code (at least the picture is not loaded), but first things first - I cannot even make the dialog appear. 我知道这段代码中还有很多其他错误(至少没有加载图片),但是首先要注意的是-我什至无法使对话框出现。 So many thanks in advance for any suppositions. 非常感谢您的任何假设。

The element <p><a href="#myModal2" id="btn2" class="btn btn-success"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p> is duplicated with same id which cause issue. 元素<p><a href="#myModal2" id="btn2" class="btn btn-success"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>与相同的id重复,这会导致问题。 Id should be unique in a page. ID在页面中应该是唯一的。

You creates same modal with element id id="myModal2" inside loop which cause another issue. 您在循环内使用元素id id="myModal2"创建了相同的模态,这会引起另一个问题。

Below is the suggestion and updated code. 以下是建议和更新的代码。

Use class name for trigger the click event. 使用class名称来触发click事件。 I have added a class show-modal to the anchor element and removed the id from it. 我向锚元素添加了一个类show-modal ,并从中删除了id Also keep the image src @Url.Content(item.ImagePath) as data attribute 还要将图像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>

Next, move the modal popup code outside of the loop and while clicking on anchor tag you can set the image src using jquery. 接下来,将模式弹出式代码移到循环外,然后在单击锚标记的同时,可以使用jquery设置图像src

See the updated code. 请参阅更新的代码。

     @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>

Hope this will help.. 希望这会有所帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在按钮单击时关闭简单的模态对话框? - How to close a simple modal dialog on a button click? 如何使用javascript自动单击dhtml模态对话框窗口按钮? - how to auto click dhtml modal dialog window button using javascript? 如何在单击按钮时将 ID 参数从一个组件传递到另一个组件? - How to pass an ID parameter to Blazorise modal on button click, from one component to another? 通过一个按钮的“单击”方法访问其他按钮 - Accessing other buttons from one button's “click” method 如何仅通过一个按钮单击事件即可隐藏或显示图像 - how to hide or show image with just one button click event 如何通过Selenium和C#根据HTML在模态对话框中单击文本为“关闭”的按钮 - How to click on the button with text as Close within a modal dialog box as per the html through Selenium and C# 如何从服务器端单击按钮时打开模式弹出窗口 - how to open modal popup on button click from server side Selenium WebDriver - 无法在模态对话框中找到并单击提交按钮 - Selenium WebDriver - Unable to find and click a Submit button on modal dialog ASP.net按钮点击不使用Jquery模态对话框触发 - ASP.net Button on click not firing using Jquery Modal Dialog 如何将一个模态对话框聚焦到另一个 - How to focus one modal dialog over another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM