我试图找到一种方法,从blazor webassembly组件内的C#方法关闭引导模式。
Bellow是我想出的一个解决方案。它涉及到使用IJSRuntime来调用javascript方法来操作引导模式。我相信还有其他方法可以解决这个问题。
引导模式可以通过javascript:关闭
创建一个javascriptwwwroot/js/site.js文件,代码为:
export function CloseModal(modalId) {
$(modalId).modal('hide');
}
在正文末尾的index.html中包含脚本:
...
<script src="js/site.js"></script>
</body>
存在一个调用模态的父组件:
ParentComponent.rarzor
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<ModalComponent />
@code {
}
然后有一个模态组件包含模态:(我们正在利用IJSRuntime从C#代码调用js(
ModalComponent剃须刀
@inject IJSRuntime js
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
@code {
IJSObjectReference JsObjectRef { get; set; }
protected override async Task OnAfterRenderAsync(bool first)
{
JsObjectRef = await js.InvokeAsync<IJSObjectReference>("import", "/js/site.js");
}
async Task SomeMethod(){
//some logic
//call the js function to close the modal
await JsObjectRef.InvokeVoidAsync("CloseModal", "#exampleModal");
}
}
现在,可以从c代码中关闭模态,例如,当调用submit方法时。
这种逻辑对我很有效。我相信还有其他更好的解决方案,尽管如此,我真的希望它能帮助到任何需要帮助的人。
和平