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);
}