i use dotnet 6 and visual studio 2022
i want inject IJSRuntime to my Page and Component
but IJSRuntime always null
this is page parent that use modal component
@page "/adminGroupRole"
<h3>AdminGroupRolePage</h3>
<button class="btn btn-primary" @onclick=modalAddNewgroup.OpenModal>Add</button>
<ModalAddNewGroupRole @ref=modalAddNewgroup/>
and code behind of page parent
public partial class AdminGroupRolePage
{
[Inject] public IJSRuntime JS { get; set; }
[Inject] public FinancialPortalDBAuth db { get; set; }
ModalAddNewGroupRole modalAddNewgroup=new();
}
i check that inject in default index works …
why ???
my code is code behind the razor blazor page
this is my code
public partial class ModalAddNewGroupRole
{
[Inject] public SweetAlert2Service SweetAlert2Service { get; set; }
[Inject] public FinancialPortalDBAuth db { get; set; }
[Inject] public IJSRuntime JS { get; set; }
DIMAuthGroup authGroupForAdd = new DIMAuthGroup();
string ID = Guid.NewGuid().ToString();
public async Task OpenModal()
{
authGroupForAdd = new();
await JS.InvokeVoidAsync("OpenModal", ID);
}
}
exact inject in index.razor works perfect
inject on pare parent not work
3
Answers
my wrong is i call OpenModal Method in razor page and blazor engine throw null exception for @ref=modalAddNewgroup and i force to new ModalAddNewGroupRole ... this wrong new ModalAddNewGroupRole() break DI ...
i moved open modal in method in parent page and after click call open modal and as @Henk Holterman Sayed remove new ModalAddNewGroupRole() and all think is OK ...
my Wrong Code :
Code Behind :
My Correct Code :
Code Behind :
This relies on Property Injection. That is an active step somewhere in the creation process of ModalAddNewGroupRole.
So how do you get the instance where you call OpenModal() on?
You need a toplevel page that has
<ModalAddNewGroupRole />
.Doing your own
var modalAddNewGroupRole = new ModalAddNewGroupRole();
won’t cut it.Try using this in your code behind