gpt4 book ai didi

javascript - 使用 JSInterop 将对象传递给 JavaScript 结果为空对象

转载 作者:行者123 更新时间:2023-12-04 01:42:26 25 4
gpt4 key购买 nike

在 ASP.Net Core 中,我正在尝试从 C# 代码为 Google map 构建基本绑定(bind)。使用 JSInterop 我可以成功地将字符串传递给 JavaScript 函数,但是当我尝试传递更复杂的对象时,该对象在 JavaScript 函数中显示为空。

我已经部分关注了 this tutorial并将其修改为使用 Google map 而不是 Bing map 。

在教程中,我找到了 TypeScript definitions让 Google map 帮助对绑定(bind)进行编码。

我有以下 razor 文件,它应该在用户单击按钮时加载 map :

@page "/sitemapper"
@inherits SiteMapperBase

<h3>Map</h3>

<div id="map" style="position: relative; width: 100%; height: 70vh;"></div>

<button class="btn btn-primary" @onclick="@OpenMap">Click me</button>

@code {
void OpenMap()
{
LoadMap();
}
}

对应.razor.cs文件具有以下 LoadMap方法:

        protected async Task LoadMap()
{
LatLng center = new LatLng(40.417268, -3.696050);
MapOptions options = new MapOptions("map", center, 8);
await JSRuntime.InvokeAsync<Task>("loadMap", options);
}

上面代码中的C#类定义在这里:

public class MapOptions
{
public string elementId;
public LatLng center;
public int zoom;

public MapOptions(string elementId, LatLng center, int zoom)
{
this.elementId = elementId;
this.center = center;
this.zoom = zoom;
}
}

public class LatLng
{
public double lat;
public double lng;

public LatLng(double latitude, double longitude)
{
lat = latitude;
lng = longitude;
}
}

在 JavaScript/TypeScript 方面,我定义了以下与 C# 类匹配的接口(interface):

interface GoogleMapOptionsInterface {
center: GoogleMapLatLngInterface,
zoom: number,
elementId: string
}

interface GoogleMapLatLngInterface {
lat: number,
lng: number
}

最后,我有一个 GoogleTsInterop.ts 文件,其中包含我的 TypeScript 代码:

/// <reference path="types/index.d.ts" />
/// <reference path="interfaces/GoogleMapsInterfaces.ts" />

let googleMap: GoogleMap;

class GoogleMap {
map: google.maps.Map;

constructor(options: GoogleMapOptionsInterface) {
console.log("constructor");
var mapElement = document.getElementById(options.elementId);
this.map = new google.maps.Map(mapElement, {
center: options.center,
zoom: options.zoom
});
}
}

function loadMap(options: GoogleMapOptionsInterface) {
new GoogleMap(options);
}

当我尝试运行它时, map 没有加载,浏览器调试器显示 options loadMap(...) 中的对象function 是一个空对象(参见 screenshot )(抱歉,我没有足够的声誉直接将图像放入)。

如果我更改我的代码,我可以成功传递具有以下内容的字符串:await JSRuntime.InvokeAsync<Task>("loadMap", "test"); .但是我想传递对象。

有没有办法做到这一点?我究竟做错了什么?谢谢

最佳答案

您可以将其作为 JsonResult 或 JSON 字符串传递吗?

MapOptions options = new MapOptions("map", center, 8);
JSRuntime.InvokeAsync<Task>("loadMap", Json(options));

MapOptions options = new MapOptions("map", center, 8);
var result = new JavaScriptSerializer().Serialize(options);
JSRuntime.InvokeAsync<Task>("loadMap", result);

关于javascript - 使用 JSInterop 将对象传递给 JavaScript 结果为空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com