简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM