10

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

7
  • In my project I used cookies to pass data between them. Or you can set a hidden div with all data you what to read from JS Commented Feb 11, 2018 at 16:51
  • Add @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) Commented Feb 11, 2018 at 21:18
  • @StephenMuecke and if my script is an external js file? How can do this then? Commented Feb 12, 2018 at 9:48
  • You need to do it in the main view (i.e. assign it as a global variable) and access value in the external file. Alternatively you could assign it to an element as a data attribute -for example <button data-value="@Model.myVar" ... > and in the js file $('button').click(function() { var value = $(this).data('value'); .... ` Commented Feb 12, 2018 at 9:53
  • ok i understand, but i have the data not in the main view. i want to access the variable from the the model class. Commented Feb 12, 2018 at 10:08

4 Answers 4

10

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)';
Sign up to request clarification or add additional context in comments.

8 Comments

And „i“ is my Variable inside my c# Code like my „myVar“ in my example right? I‘ll test it
tried it and did not work for me. it only prints out "@i". Could you provide a working example?
thanks. i tried it again but anyway no change. Does this only works if i use the javascript code directly inside my view inside the <script>-Tags? If i do it this way your solution works very well, but not if i have my code inside a external js file which to which i reference via the <script>-Tag. Any solution for this? i added an example in my question.
@Opa114 you can extract value in inline script and pass it in your external js file's function.
oh yeah this works but in this case isn't it better to let the whole javascript stuff inline inside the view? And another clean and simple solution to access the data from a model in an external javascript file is not possible or?
|
10

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();

Comments

7

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.

Comments

1

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.

1 Comment

Thank you. After few hours i found this working code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.