Reputation: 548
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
Upvotes: 10
Views: 22919
Reputation: 171
I had the same issue and found much easier solution for parsing arrays/lists. Consindering you have this view model:
public class MyViewModel
{
// List
public List<string> MyList { get; set; }
// a simple variable
public string MyVar{ get; set; }
}
You can simply use this:
<script>
var myList = @Json.Serialize(Model.MyList);
</script>
The same syntax can be used for the single object.
Upvotes: 1
Reputation: 4844
Here is an example with an strong typed ViewModel and an C#-list which will be serialized into an js-array.
The ViewModel:
namespace ProjectName.ViewModels
{
public class MyViewModel
{
// List
public List<string> MyList { get; set; }
// a simple variable
public string MyVar{ get; set; }
}
}
In the view use the following code to pass the list of your C#-ViewModel to an JavaScript array.
The View (*.cshtml):
@model MyProject.ViewModels.MyViewModel
<script type="text/javascript">
var myArray = JSON.parse('@Json.Serialize(@Model.MyList)');
var myVar = '@Model.MyVar';
</script>
Instead of the list you can also use an object.
Upvotes: 7
Reputation: 961
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)';
Upvotes: 9
Reputation: 34189
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();
Upvotes: 10