从Javascript调用.net方法

暨正真
2023-12-01

Calling .Net From JavaScript
Razor

@page "/callingdotnetfromjavascript"
@inject IJSRuntime JSRuntime
<h1>Text received</h1>
<ul>
    @foreach (string text in TextHistory)
    {
        <li>@text</li>
    }
</ul>
@code
{
    List<string> TextHistory = new List<string>();
    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            var dotNetReference = DotNetObjectReference.Create(this);
            JSRuntime.InvokeVoidAsync("BlazorUniversity.startRandomGenerator", dotNetReference);
        }
    }
    [JSInvokable("AddText")]
    public void AddTextToTextHistory(string text)
    {
        TextHistory.Add(text.ToString());
        while (TextHistory.Count > 10)
            TextHistory.RemoveAt(0);
        StateHasChanged();
        System.Diagnostics.Debug.WriteLine("DotNet: Received " + text);
    }
}

Js文件

var BlazorUniversity = BlazorUniversity || {};
BlazorUniversity.startRandomGenerator = function (dotNetObject) {
    setInterval(function () {
        let text = Math.random() * 1000;
        console.log("JS: Generated " + text);
        dotNetObject.invokeMethodAsync('AddText', text.toString());
    }, 1000);
};


 类似资料: