将Razor变量转换为Javascript [英] Razor variable into Javascript

查看:54
本文介绍了将Razor变量转换为Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Razor从模型变量中设置JavaScript变量,但无法找出问题所在.在CSHTML页面中,我尝试了以下方法:

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";

然后,当我访问变量时,几乎总是得到错误 test1 is undefined .如果我将变量设置为 var test1 ='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>

这篇关于将Razor变量转换为Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆