Blazor 新手,如果这只是糟糕的代码,我深表歉意,但我在让 Javascript Interop 在这里工作时遇到问题。我试图让用户允许通过提交按钮进行地理位置定位。我没有收到任何错误,但也没有触发 JSInvokable 方法。
我的 Blazor 页面:
@using Microsoft.AspNetCore.Components.Forms
@inject IJSRuntime JsRuntime
<EditForm EditContext="editContext" FormName="MessageForm" OnValidSubmit="@GetLoc">
<button class="btn btn-primary" data-callback="onSubmit" data-action="GetLocation">Share Your Location to Load</button>
</EditForm>
@code
{
private DotNetObjectReference<Dealer>? dotNet;
private double geoLat, geoLong;
private async Task GetLoc()
{
try
{
dotNet = DotNetObjectReference.Create(this);
var result = await JsRuntime.InvokeAsync<object>("blazorGetLocation", dotNet);
}
catch (Exception ex)
{
// Handle exceptions
}
}
[JSInvokable]
public void ReturnLocation(double latitude, double longitude)
{
geoLat = latitude;
geoLong = longitude;
}
[JSInvokable]
public void ReturnError(string errorMessage)
{
geoLat = 0;
geoLong = 0;
}
private EditContext? editContext;
[SupplyParameterFromForm]
public GeoLocation? geoLoc { get; set; }
protected override async Task OnInitializedAsync()
{
geoLoc ??= new();
editContext = new(geoLoc);
}
}
我的Javascript:
window.returnLocation = function (dotNet) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
dotNet.invokeMethodAsync('ReturnLocation', position.coords.latitude, position.coords.longitude);
});
} else {
dotNet.invokeMethodAsync('ReturnError', 'Some error text.');
}
};
在阅读(并重新阅读)我能找到的所有内容后,问题来自我试图调用 JsRuntime.InvokeAsync 方法的地方。
通过使用 @rendermode InteractiveServer 并从 OnAfterRenderAsync 覆盖中调用“var result = wait JsRuntime.InvokeAsync("blazorGetLocation", dotNet)”,代码现在可以正常工作。