问题描述
如何在视图中调用javascript函数(cshtml)并传递一些字符串变量(在视图中定义)作为函数调用的参数?
javascriptFunction('param1','param2')。
string y =这是一个字符串
string x = 另一个
javascriptFunction(y,x)
我试过javascriptFunction(@y, @x),javascriptFunction('@ y','@x')但这不起作用
JavaScript代码和服务器端代码之间。还要编码你的javascript字符串:
@ {
string y =这是一个字符串;
string x =another;
}
< script type =text / javascript>
函数javascriptFunction(第一,第二)
{
alert(first +''+ second);
}
javascriptFunction(@ Html.Raw(Json.Encode(y)),@ Html.Raw(Json.Encode(x)));
< / script>
How can I call a javascript function within a view(cshtml) and pass some string variables (defined in the view)to be used as parameters for the function call?
Say the function javascriptFunction uses 2 parameter. I will usually call it as javascriptFunction('param1', 'param2')
. But now I want to pass it some variables.
string y = "this is a string"
string x = "another"
javascriptFunction(y, x)
I have tried javascriptFunction(@y, @x), javascriptFunction('@y', '@x') but this does not work
You have to distinguish between javascript code and server-side code. Also encode your javascript strings:
@{
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>
这篇关于MVC:使用视图的字符串变量作为javascript函数调用的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!