How to use a razor page string variable in javascript? - show alert with C# string

512 views Asked by At

I am trying to use razor pages to make an asp.net core v. 2.0 website.

And I want to get an ipaddress from the C# code and use it to call a webapi from javascript. - but I'm stuck on showing an alert from javascript

basically my C# is that simple.

 class Aclass {
  public string Text{get;set;}
 }

and the javascript is like this:

    var text = @Model.Text;
    alert (text);

( and I have the model set for the page..)

does anyone know how to get the Text to show?

2

There are 2 answers

0
Farhad Bagherlo On
<script>
var text = '@(Model.Text)';
    alert (text);
</script>
0
kfn On

the javascript fix was found here: Using Razor within JavaScript

basically it is a combination of '@ and ( that makes it all work.

var text = '@(Model.Text)'; alert(text);

and boom your flying..