I have a .NET Core 2 Razor view with the underlying model inside a *.cshtml.cs file. Let's say I have a string like this:
public string myVar = "hello world";
How can I access this variable (data) inside my external JavaScript file?
I need this for example in the following case. I'm using the jVectorMap jquery library. There I can select multiple regions of the map. I have to save the selected regions (let's say in an array of unique ids) so that I can pre-populate the map with the selected regions, if the user loads the special page with the map inside. And the data (selected regions) can be different do different users. So I have to store the data for each user and the have to load the data. jVectorMap has an API function which allows to pre-populate the map with some data.
But how can I access my saved variable / data inside the external javascript file?
EDIT: I added an example here: https://dotnetfiddle.net/QV4Fi1
@inject IJsonHelper Json;in your view, and then inside your script -var value = @Html.Raw(Json.Serialize(Model.myVar))(assumes your scripts is not in an external js file)valuein the external file. Alternatively you could assign it to an element as adataattribute -for example<button data-value="@Model.myVar" ... >and in the js file$('button').click(function() { var value = $(this).data('value');.... `