使用IJSRuntime在blazor中包装引导模式



是否可以通过IJSRuntime获取对Bootstrap 5bootstrap.Modal的引用,并保存对该实例的引用以供以后使用?

示例:

我可以用这种方法显示一个模态:

await _jsRuntime.InvokeVoidAsync("eval", $"new bootstrap.Modal(document.getElementById('myId')).show()");

但是我不能以同样的方式隐藏它,因为我需要存储对new bootstrap.Modal创建的引用。如何动态地做到这一点(我有一个引导模式组件(而不必编写javascript?有没有什么方法可以保存变量并在以后通过IJSRuntime引用它们?

经过大量搜索,我发现eval永远不是解决方案。我不是一个JavaScript开发人员,但我得到了这个:

BootstrapModal.rarzor

@inject IJSRuntime _jsRuntime;
<div class="modal fade" id="@Id" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
@ChildContent
</div>
</div>
</div>
@code {
[Parameter]
public string Id { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
public dynamic Parameter { get; private set; }
protected override void OnInitialized()
{
if (string.IsNullOrEmpty(Id))
{
Id = Guid.NewGuid().ToString();
}
}
public async Task Show(dynamic parameter = null)
{
Parameter = parameter;
await _jsRuntime.InvokeVoidAsync("BootstrapModal.ShowModal", Id);
}
public async Task Hide()
{
await _jsRuntime.InvokeVoidAsync("BootstrapModal.HideModal");
}
}

BootstrapModalInterop.js

window.BootstrapModal = {};
window.BootstrapModal.OpenedModal = null;
window.BootstrapModal.ShowModal = (id) => {
if (window.BootstrapModal.OpenedModal != null) {
window.BootstrapModal.HideModal();
}
window.BootstrapModal.OpenedModal = new bootstrap.Modal(document.getElementById(id));
window.BootstrapModal.OpenedModal.show();
}
window.BootstrapModal.HideModal = () => {
if (window.BootstrapModal.OpenedModal == null) {
return;
}
window.BootstrapModal.OpenedModal.hide();
window.BootstrapModal.OpenedModal = null;
}

确保您引用了主机文件中的BootstrapModalInterop.js文件。

现在,您可以从blazor代码中以本机方式打开和关闭模态。

示例用法:

...
<button class="btn btn-danger" @onclick="async () => await _deleteModal.Show(discountCode.Id)"><i class="fas fa-trash"></i></button>
...
<BootstrapModal @ref="_deleteModal">
<div class="modal-header">
<h5 class="modal-title">
Delete Discount Code
</h5>
</div>
<div class="modal-body">
<p>
Are you sure that you want to delete this discount code? This cannot be undone!
</p>
</div>
<div class="modal-footer">
<button @onclick="async () => await _deleteModal.Hide()" class="btn btn-secondary">Close</button>
<button @onclick="async () => await Delete((int)_deleteModal.Parameter)" class="btn btn-outline-danger">Delete</button>
</div>
</BootstrapModal>
@code 
{
private BootstrapModal _deleteModal;
}

parameter属性是可选的,但我用它来解析我要删除的项目的ID。稍后我可以使用(int)_deleteModal.Parameter获得这个ID。我选择了一个dynamic类型,这样我就可以以任何方式进行解析。

最新更新