在 razor 语法中嵌入 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4332253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
embedding javascript variable within razor syntax
提问by Emad
I have a method that looks like this
我有一个看起来像这样的方法
function endcall_click(leadid) {
document.location = '@Url.Action("index","dispo",new{id=leadid})/';
}
Of course it doesn't work because it treats "leadid" as a server side variable but I want to inject the javascript variable passed into the method.
当然它不起作用,因为它将“leadid”视为服务器端变量,但我想注入传递给方法的 javascript 变量。
I tried wrapping lead id in but that didn't work.
我尝试将潜在客户 ID 包裹起来,但这没有用。
function endcall_click(leadid) {
document.location = '@Url.Action("index","dispo",new{id="<text>leadid</text>"})/';
}
Any ideas?
有任何想法吗?
回答by Darin Dimitrov
You can't inject javascript variable to a script that is evaluated at the server simply because at the moment this script executes and generates the output this variable hasn't yet come to existence. The only way to achieve this is to manipulate the resulting string:
您不能将 javascript 变量注入到在服务器上评估的脚本中,因为在此脚本执行并生成输出时,此变量尚未存在。实现这一点的唯一方法是操作结果字符串:
function endcall_click(leadid) {
document.location = '@Url.Action("index", "dispo")/' + leadid;
}
The drawback is that this assumes manipulating the routes in javascript and if you decide to change them on the server the code might break.
缺点是这假定在 javascript 中操作路由,如果您决定在服务器上更改它们,代码可能会中断。
回答by SZL
I finally found the solution (*.vbhtml):
我终于找到了解决方案(*.vbhtml):
<script type="text/javascript">
function razorsyntax() {
/* Double */
@(MvcHtmlString.Create("var szam =" & mydoublevariable & ";"))
alert(szam);
/* String */
var str = '@stringvariable';
alert(str);
}
</script>

