MVC:使用视图的字符串变量作为javascript函数调用的参数 [英] MVC: Use string variables of a view as parameter to a javascript function call

查看:126
本文介绍了MVC:使用视图的字符串变量作为javascript函数调用的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在视图中调用javascript函数(cshtml)并传递一些字符串变量(在视图中定义)作为函数调用的参数?



<说功能javascript功能使用2个参数。我通常会把它称为 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>

在JavaScript中使用Razor


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>

Using Razor within javascript

这篇关于MVC:使用视图的字符串变量作为javascript函数调用的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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