使用JSInterop将对象传递给JavaScript会导致空对象

时间:2019-07-03 15:29:25

标签: javascript c# typescript asp.net-core blazor

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

我已部分遵循this tutorial,并将其修改为使用Google地图而不是必应地图。

与本教程一样,我发现TypeScript definitions用于Google Maps来帮助对绑定进行编码。

我有以下剃刀文件,当用户单击按钮时,该文件应加载地图:

@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 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);
}

当我尝试运行此命令时,地图不会加载,并且在浏览器中查看调试器会发现options函数中的loadMap(...)对象是一个空对象(请参见screenshot )(对不起,我没有足够的声誉直接将图片放入)。

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

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

1 个答案:

答案 0 :(得分:0)

您可以将其作为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);