Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject in blazor code behind .razor.cs file? IJSRuntime for example

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?

like image 738
Kyle Avatar asked Dec 11 '19 17:12

Kyle


People also ask

How can you separate the markup from the code behind in a razor page?

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.

How do you inject NavigationManager Blazor?

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 .

How do I add a razor file to CS?

Right click on Pages folder then go to Add and then click class. Give the file name as Counter. razor. cs and click Add.


1 Answers

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')");
    }
}
like image 171
Kyle Avatar answered Oct 16 '22 19:10

Kyle