Razor variable into Javascript

丶灬走出姿态 提交于 2019-12-31 05:31:47

问题


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>


来源:https://stackoverflow.com/questions/45285302/razor-variable-into-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!