简体   繁体   中英

Accessing JS Variables with C#

I've got a variable which is set in a final script tag on page load, as this is required due to accessing the DOM (using a 3rd party library). I want to access my variable, however I get "undefined" when accessing it via C# (ASP Web Application).

How can I access this?

If I run the following from C#:

ClientScript.RegisterStartupScript(GetType(), "hwa", "hello();", true);

I get the following error: https://i.stack.imgur.com/veiLB.png

My hello function is:

function hello() {
 alert(mapData);
}

This mapData variable is set in a script tag at the end of the body, my original code was to call a JS function AFTER the site loaded, however it comes up as undefined via C# yet shows up if I use the Web Console.

Full Script:

function createMap() {
mapData = L.map('map', {
    center: [20.0, 5.0],
    minZoom: 2,
    zoom: 5
});

L.mapData = mapData;

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: ['a', 'b', 'c']
}).addTo(L.mapData);
}

function createMarker(long, lat, type) {
    alert(L.mapData);
    L.marker([long, lat], { icon: L.icon({ iconUrl: 'Content/img/' + type + '.png', iconSize: [50, 60], iconAnchor: [22, 94], popupAnchor: [-3, -76], }) }).addTo(L.mapData);
}

function hello() {
    alert(mapData);
}

It looks like your hello method is being called before mapData is being instantiated.

I do not see where it is being instantiated but you could change your register script as follows:

ClientScript.RegisterStartupScript(GetType(), "hwa", "createMap(); hello();", true);

Note that you may want to add a hello callback to your create function.

More info as to what you are trying to do here may also be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM