I am trying to pass my string variable (even boolean) on my cshtml view to my javascript section. I can successfully pass the value from razor section to javascript if its integer. But what I want to accomplish is to pass the string value. Here is my sample code from my .cshtml:
string strAnnouncement = "My announcement";
int intCounterValue = 1200;
To receive the value on Javascript, here is my code:
//Cannot get the value, always error on Developer Tool console
var SessAnnouncement = @strAnnouncement;
//Can get the value successfully
var SessInitTimer = @intCounterValue;
As you can see, I can get the value via javascript on SessInitTimer which is 1200. But on SessAnnouncement, I get a Uncaught ReferenceError: My announcement is not defined.
How can I get the strAnnouncement value on my razor section and pass it on script section?
They are treated as variable and since you have not defined them you get the said error.
You need to wrap in quotes to be treated as string.
var SessAnnouncement = "@strAnnouncement";
A better approach would be to use JSON.Encode()
method
var SessAnnouncement = @Html.Raw(Json.Encode(strAnnouncement));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With