0

如何在视图(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') 但这不起作用

4

2 回答 2

1

您必须区分 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

于 2013-01-08T20:09:51.240 回答
0

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

ASP.NET MVC 在 JavaScript 中使用 ViewData

于 2013-01-08T20:04:06.227 回答