How can i get Javascript Callback in .Net Blazor?

≡放荡痞女 提交于 2019-12-23 11:49:25

问题


Is there a way to add callback to Javascript and get the result in Blazor? Apart from JS Promises.

for example, let say i want to load a file

Javascript Code

window.readFile = function(filePath, callBack) {
    var reader = new FileReader();
    reader.onload = function (evt) {
        callBack(evt.target.result);
    };
    reader.readAsText(filePath);
}

Can i have something like this in Blazor C#

    // read file content and output result to console
    void GetFileContent() {
        JsRuntime.InvokeAsync<object>("readFile", "file.txt", (string text) => {
            Console.Write(text);
        });
    }

Or Maybe something like this

    // read with javascript
    void ReadFileContent() {
        JsRuntime.InvokeAsync<object>("readFile", "file.txt", "resultCallbackMethod");
    }

    // output result callback to console
    void resultCallbackMethod(string text) {
        Console.Write(text);
    }

Thanks


回答1:


UPDATE 1:

After re-reading your question, I think this would cover your 2nd example

I think you have the option of implementing a JS proxy function that handle the calling. Something like this:

UPDATE 2:

Code was updated with a functional (but not deeply tested) version, you can also find a working example in blazorfiddle.com

JAVASCRIPT CODE

// Target Javascript function
window.readFile = function (filePath, callBack) {

    var fileInput = document.getElementById('fileInput');
    var file = fileInput.files[0];

    var reader = new FileReader();

    reader.onload = function (evt) {
        callBack(evt.target.result);
    };

    reader.readAsText(file);

}

// Proxy function
// blazorInstance: A reference to the actual C# class instance, required to invoke C# methods inside it
// blazorCallbackName: parameter that will get the name of the C# method used as callback
window.readFileProxy = (instance, callbackMethod, fileName) => {

    // Execute function that will do the actual job
    window.readFile(fileName, result => {
        // Invoke the C# callback method passing the result as parameter
        instance.invokeMethodAsync(callbackMethod, result);
    });

}

C# CODE

@page "/"

@inject IJSRuntime jsRuntime

<div>
    Select a text file:
    <input type="file" id="fileInput" @onchange="@ReadFileContent" />
</div>
<pre>
    @fileContent
</pre>

Welcome to your new app.

@code{

    private string fileContent { get; set; }

    public static object CreateDotNetObjectRefSyncObj = new object();

    public async Task ReadFileContent(UIChangeEventArgs ea)
    {
        // Fire & Forget: ConfigureAwait(false) is telling "I'm not expecting this call to return a thing"
        await jsRuntime.InvokeAsync<object>("readFileProxy", CreateDotNetObjectRef(this), "ReadFileCallback", ea.Value.ToString()).ConfigureAwait(false);
    }


    [JSInvokable] // This is required in order to JS be able to execute it
    public void ReadFileCallback(string response)
    {
        fileContent = response?.ToString();
        StateHasChanged();
    }

    // Hack to fix https://github.com/aspnet/AspNetCore/issues/11159    
    protected DotNetObjectRef<T> CreateDotNetObjectRef<T>(T value) where T : class
    {
        lock (CreateDotNetObjectRefSyncObj)
        {
            JSRuntime.SetCurrentJSRuntime(jsRuntime);
            return DotNetObjectRef.Create(value);
        }
    }

}



回答2:


I believe that you are looking for the info on the documentation here: https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.0#invoke-net-methods-from-javascript-functions

It shows how to call the Razor.Net from Javascript. The documentation has more information, but essentially you will need the [JSInvokable] attribute on the method in razor, and calling via DotNet.invokeMethod in javascript.




回答3:


Thanks for that @Henry Rodriguez. I created something out of it, and i believed it might be helpful as well.

Note that DotNetObjectRef.Create(this) still works fine in other method. It is only noted to have problem with Blazor lifecycle events in preview6. https://github.com/aspnet/AspNetCore/issues/11159.

This is my new Implementation.

<div>
    Load the file content
    <button @click="@ReadFileContent">Get File Content</button>
</div>

<pre>
    @fileContent
</pre>

Welcome to your new app.

@code{
string fileContent;

//The button onclick will call this.
void GetFileContent() {
     JsRuntime.InvokeAsync<object>("callbackProxy", DotNetObjectRef.Create(this), "readFile", "file.txt", "ReadFileCallback");
}


//and this is the ReadFileCallback

[JSInvokable] // This is required for callable function in JS
public void ReadFileCallback(string filedata) {
    fileContent = filedata;
    StateHasChanged();
}

And in blazor _Host.cshtml or index.html, include the callback proxy connector

// Proxy function that serves as middlemen
 window.callbackProxy =  function(dotNetInstance, callMethod, param, callbackMethod){
    // Execute function that will do the actual job
    window[callMethod](param, function(result){
          // Invoke the C# callback method passing the result as parameter
           return dotNetInstance.invokeMethodAsync(callbackMethod, result);
     });
     return true;
 };



// Then The Javascript function too

 window.readFile = function(filePath, callBack) {
    var reader = new FileReader();
    reader.onload = function (evt) {
        callBack(evt.target.result);
    };
    reader.readAsText(filePath);
}

This works perfectly for what i needed, and it is re-usable.



来源:https://stackoverflow.com/questions/56627649/how-can-i-get-javascript-callback-in-net-blazor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!