温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Using JSInterop to pass object to JavaScript results in empty object
asp.net-core blazor c# javascript typescript

c# - 使用JSInterop将对象传递给JavaScript会导致对象为空

发布于 2020-03-27 11:57:01

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

我部分地遵循了本教程,并将其修改为使用Google Maps而不是Bing Maps。

就像在本教程中一样,我已经找到了Google Maps的TypeScript定义来帮助编码绑定。

我有以下剃刀文件,当用户单击按钮时,该文件应加载 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 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未加载,并且在浏览器中查看调试器,结果显示optionsloadMap(...)函数中的对象是空对象(请参见屏幕截图)(对不起,我没有足够的声誉将图像直接放入)。

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

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

查看更多

查看更多

提问者
galen
被浏览
186
Vogel T. 2019-07-04 00:40

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