im trying to link my page’s button with dialog that i have made before. it is a simple code, i have watched many tutorials and none of them solved mine
here’s my code
page.razor
@page "/datapegawai"
@inject IJSRuntime js
@attribute [StreamRendering]
<PageTitle>Data Pegawai</PageTitle>
<h1>Data Pegawai</h1>
<div class ="container">
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="header">
<button @onclick="ShowDialog" class="btn btn-primary float-end">
Add Product
</button>
</div>
</div>
</div>
</div>
</div>
<DialogComponent>
</DialogComponent>
@code {
private async Task ShowDialog()
{
await js.InvokeVoidAsync("myDialogFunction");
}
}
dialog.js
window.myDialogFunction = function () {
document.getElementById('my-dialog').showModal();
}
DialogComponent.razor
<div>
<dialog id="my-dialog" @onclose="OnClose" @oncancel="OnCancel">
<p>Hi Di sana!</p>
<form method="dialog">
<button>TUTUP!</button>
<button>BATAL!</button>
</form>
</dialog>
</div>
@code {
string message;
void OnClose(EventArgs e) => message += "onclose,";
void OnCancel(EventArgs e) => message += "oncancel,";
}
i have tried to add button to the DialogComponent.razor just to make sure the js worked. It did work, but i still have no idea how to connect my page.razor’s button with the js. thank you
7
In static render, button onclick event won’t work. However you could use form submit as a replacement to make button submit work.
...
<div class="header">
<button type="submit" form="form1">Add Product</button>
</div>
...
<form id="form1" method="post" @onsubmit="ShowDialog" @formname="form1">
<AntiforgeryToken></AntiforgeryToken>
</form>
@code{
private async Task ShowDialog()
{
await js.InvokeVoidAsync("myDialogFunction");
}
}
Just note that the button element hasn’t to be in the form element. Only make sure the buttom’s form
attribute equals to the corresponding form’s id
.