With a normal single page razor component in Blazor. I can inject IJSRuntime
like this at the top of the page:
@inject IJSRuntime JSRuntime
If I create a code behind .razor.cs file for the component, how do I inject something like IJSRuntime
into the code behind file?
razor file mentioned above becomes the Counter class once compiled. Therefore, to separate HTML and code from each other, the code-behind must use the partial modifier when declaring a class (line #1). Then move the codes inside the @code block to the Counter class.
Access to browser navigation from Blazor is provided via the NavigationManager service. This can be injected into a Blazor component using @inject in a razor file, or the [Inject] attribute in a CS file. The NavigationManager service has two members that are of particular interest; NavigateTo and LocationChanged .
Right click on Pages folder then go to Add and then click class. Give the file name as Counter. razor. cs and click Add.
In the code behind razor.cs file, IJSRunTime
or others can be injected with the [Inject]
attribute
public partial class BillingDashboard
{
[Inject]
IJSRuntime JSRuntime { get; set; }
protected override async Task MyFunction()
{
await JSRuntime.InvokeVoidAsync("console.log('test')");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With