MVC:使用视图的字符串变量作为javascript函数调用的参数

MVC: Use string variables of a view as parameter to a javascript function call

本文关键字:javascript 参数 函数调用 变量 字符串 视图 MVC      更新时间:2023-09-26

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

假设函数javascriptFunction使用2个参数。我通常称它为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>

在javascript中使用Razor

您可以使用此链接中的答案加载一些变量,并将它们传递给您的函数。

ASP。