I injected the IJSRuntime service into my code, and I’m trying to create an extension method to reduce the mess of having to use await js.InvokeAsync<bool>("confirm", "my message")
to simply the created method, which wold be something like await js.ConfirmMethod("my message")
However, after creating the extension method, it states: "’IJSRuntime’ does not contain a definition for ‘confirMethod’ and no accessible extension method ‘confirMethod’ accepting a first argument of type ‘IJSRuntime’ could be found"
The main component
@inject IJSRuntime js
@code
{
public int one = 1;
[Parameter] public List<Books> ?Library {get; set;}
public async Task deleteBook(Books book)
{
var confirm = await js.confirMethod($"Are you sure you want to delete {book.bookName}?");
@if(confirm)
{
Console.WriteLine($"The book {book.bookName} by {book.author} has been deleted");
Library.Remove(book);
}
}
}
The extension method class
using Microsoft.JSInterop;
namespace blazorTestApp.Client.Classes_FE
{
public static class IJSExtentionMethods
{
public static async ValueTask<bool> confirMethod(this IJSRuntime js, string message)
{
bool confirm = await js.InvokeAsync<bool>("confirm", message);
return confirm;
}
}
}
2
Answers
The razor component can not find the extension method, because the namespace is not imported anywhere.
There are a few ways you can solve this and you should choose whichever is appropriate for you.
blazorTestApp.Client.Classes_FE
namespace to theImports.razor
Microsoft.JSInterop
this is sometimes done for discoverability reasons@using blazorTestApp.Client.Classes_FE
to the top of your razor component to import the namespaceHere’s your provided code in a standalone reproducible project.
It works, so your problem is in your namespacing. first declare the namespace where you’re using the extension and then fix your usings and imports files.
A class to define your extension method:
And it being used in a page: