无论相似按钮的数量如何,只需单击一个按钮即可加载模态对话框 - 如何解决?
Modal dialog loads just from the click on one button regardless of the number of similar buttons - how to fix it?
我在视图中创建了一个 Datatables table,其中包含触发模态对话框的按钮。按钮仅在满足某些条件时出现(正是当图像路径不为空时),并且条件语句在视图内。模态对话框由按钮触发,但只有一个按钮 - 它不会由任何其他有条件出现的按钮触发,尽管它们由 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; }
}
}
我知道这段代码中还有很多其他错误(至少图片没有加载),但首先要做的是 - 我什至无法显示对话框。非常感谢任何假设。
元素 <p><a href="#myModal2" id="btn2" class="btn btn-success"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>
与相同的 id
重复,这会导致问题。 ID在一个页面中应该是唯一的。
您在循环内使用元素 ID id="myModal2"
创建了相同的模式,这导致了另一个问题。
以下是建议和更新后的代码。
使用class
名称触发click
事件。我在锚元素中添加了 class 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>
接下来,将模态弹出代码移到循环之外,同时单击锚标记,您可以使用 jquery 设置图像 src
。
查看更新后的代码。
@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>
希望这会有所帮助..
我在视图中创建了一个 Datatables table,其中包含触发模态对话框的按钮。按钮仅在满足某些条件时出现(正是当图像路径不为空时),并且条件语句在视图内。模态对话框由按钮触发,但只有一个按钮 - 它不会由任何其他有条件出现的按钮触发,尽管它们由 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; }
}
}
我知道这段代码中还有很多其他错误(至少图片没有加载),但首先要做的是 - 我什至无法显示对话框。非常感谢任何假设。
元素 <p><a href="#myModal2" id="btn2" class="btn btn-success"> <span class="glyphicon glyphicon-eye-open"></span> Открыть</a></p>
与相同的 id
重复,这会导致问题。 ID在一个页面中应该是唯一的。
您在循环内使用元素 ID id="myModal2"
创建了相同的模式,这导致了另一个问题。
以下是建议和更新后的代码。
使用class
名称触发click
事件。我在锚元素中添加了 class 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>
接下来,将模态弹出代码移到循环之外,同时单击锚标记,您可以使用 jquery 设置图像 src
。
查看更新后的代码。
@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>
希望这会有所帮助..