Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  53] [ 6]  / answers: 1 / hits: 20193  / 6 Years ago, sun, february 11, 2018, 12:00:00

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


More From » c#

 Answers
45

You can get C#/Razor values as a string easily enough.



<script type=text/javascript>
var i = parseInt('@Model.i');
</script>


Or you can try with below given options.



Option 1:



var myVar = '@Model.MyVar';
var name = '@Model.Name';


Option 2:



var myVar ='@Html.Raw(Model.MyVar)';
var name = '@Html.Raw(Model.Name)';

[#55193] Thursday, February 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tierney

Total Points: 45
Total Questions: 101
Total Answers: 94

Location: Sudan
Member since Thu, May 7, 2020
4 Years ago
;