Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor variable into Javascript

I am trying to set a JavaScript variable from a model variable using Razor, and can't figure out what is wrong. In the CSHTML page, I've tried the following ways:

<script>
   var test1 = @Model.testVariable;
   var test2 = @(Model.testVariable);
   var test3 = <text>@Model.testVariable</text>
   var test4 = @Html.Raw(Model.testVariable);
</script>

In the Model, test variable is defined like

public string testVariable { get; set; }

In the controller, I am setting the variable like:

model.testVariable = "x";

Then when I access the variable, I almost always get the error test1 is undefined. If I set the variable like var test1 = 'x', then it works fine. It is only having a problem when I am grabbing the variable from the model

$(document).ready(function () {
   alert(test1);
}
like image 491
Greg Senne Avatar asked Jan 30 '23 22:01

Greg Senne


1 Answers

If you need to set a variable to a string literal, then it needs to be enclosed in quotes. For example:

<script>
   var test1 = '@Model.testVariable';
</script>
like image 99
DavidG Avatar answered Feb 02 '23 17:02

DavidG