Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Razor String Variable to Javascript String Variable in MVC

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?

like image 274
Willy David Jr Avatar asked Oct 19 '16 08:10

Willy David Jr


1 Answers

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));
like image 182
Satpal Avatar answered Oct 17 '22 02:10

Satpal