How do I initiate call to DotNet method from JS.
- My index.razor calls JS 'Create' function and passes json filename that need to be opened.
- index.js opens the file and parses its content. As you could see that only after the file is parsed (after satifysing (data[i].name === "something") condition), window.sendName can return value to blazor.
- So, I would like to know how JS(index.js) could initiate call to blazor by itself, rather than initiated from navbar.razor.
- Because when call initiated from navbar.razor as below, navbar is loaded before json is parsed, so cant return proper value.
My code:
Index.razor:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JSRuntime.InvokeVoidAsync("Create", fileName);
}
JS:
function Create(fileName) {
$.getJSON(fileName, function (data) {
data.forEach((eachline, i) => {
if (data[i].name === "something") {
window.sendName= () => {
var val = "Abc";
return val;
}
}
}
}
}
NavBar.Razor:
<a href="" @onclick=getName>GetName</a>
public string? Name { get; set; }
[JSInvokable]
private async Task getName()
{
Name= await JSRuntime.InvokeAsync<string>("sendName");
}
I tried using example in below link. But doesn't seem to work as I expect. https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-6.0#class-instance-examples