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
Option1
Model
public class MyModel
{
public string MyProperty {get;set;}
}
cshtml
@model WebAppp.MyModel
@Html.HiddenFor(x=>x.MyProperty)
javascript
$("#MyProperty").val();
Option 2
In controller you can store in ViewData or ViewBag
ViewBag["MyPropertyValue"] ="something";
in cshml ( i havent tried but should work)
@Html.Hidden("MyProperty",ViewData["MyPropertyValue"],new { @class = "someclass" })
javascript
$("#MyProperty").val();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With