Razor variable into Javascript

2019-03-06 09:52发布

问题:

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

回答1:

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>