Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing .net core model data to external javascript?

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

like image 969
Opa114 Avatar asked Feb 11 '18 16:02

Opa114


1 Answers

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();
like image 134
LP13 Avatar answered Sep 27 '22 19:09

LP13