10

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?

1
  • 1
    You have to enclose your C# variable into single or double quote if you want to access it in javascript. ex: var SessAnnouncement = '@strAnnouncement'; Commented Oct 19, 2016 at 8:40

1 Answer 1

25

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

4 Comments

That works for single values. If there are newlines in the string, JavaScript throws a syntax error exception.
@Suncat2000, for multiple line use backtick i.e. `@strAnnouncement`. However, I would recommend the second approch
Thanks for the tip, but that works only if all your browsers support template literals. Internet Explorer does not. I ended up using @(new HtmlString(HttpUtility.JavaScriptStringEncode(Model.XmlProcessedText, true))) to encode the string and escape quotes. It worked perfectly.
Your suggestion was the only one that worked for me, @Suncat2000, although I still had to wrap it in upticks so that Javascript recognised it as a string and not a variable name.

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.