MVC:使用视图的字符串变量作为javascript函数调用的参数
如何在视图(cshtml)中调用javascript函数并传递一些字符串变量(在视图中定义)作为函数调用的参数 假设函数javascriptFunction使用2个参数。我通常将其称为MVC:使用视图的字符串变量作为javascript函数调用的参数,javascript,function,razor,parameters,Javascript,Function,Razor,Parameters,如何在视图(cshtml)中调用javascript函数并传递一些字符串变量(在视图中定义)作为函数调用的参数 假设函数javascriptFunction使用2个参数。我通常将其称为javascriptFunction('param1','param2')。但是现在我想给它传递一些变量 string y = "this is a string" string x = "another" javascriptFunction(y, x) 我尝试过javascriptFunction(@y,@x
javascriptFunction('param1','param2')
。但是现在我想给它传递一些变量
string y = "this is a string"
string x = "another"
javascriptFunction(y, x)
我尝试过javascriptFunction(@y,@x)、javascriptFunction('@y','@x'),但这不起作用您可以使用此链接中的答案加载一些变量,并将它们传递到您的函数中
您必须区分javascript代码和服务器端代码。还要对javascript字符串进行编码:
@{
string y = "this is a string";
string x = "another";
}
<script type="text/javascript">
function javascriptFunction(first,second)
{
alert(first+' '+second);
}
javascriptFunction(@Html.Raw(Json.Encode(y)), @Html.Raw(Json.Encode(x)));
</script>
@{
string y=“这是一个字符串”;
字符串x=“另一”;
}
函数javascriptFunction(第一,第二)
{
警报(第一次+第二次);
}
javascriptFunction(@Html.Raw(Json.Encode(y)),@Html.Raw(Json.Encode(x));
尝试用引号括起来->(“@y”,“@x”)尝试过,但出现语法错误\n尝试用单引号括起来上面答案中的两个变量。