C# 如何在mvc3视图中的foreach中调用javascript函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11789651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:16:03  来源:igfitidea点击:

how to call a javascript function in foreach in mvc3 view

c#javascriptasp.net-mvcasp.net-mvc-3

提问by user1573165

I want to call a JavaScript function in c# code in asp.net mvc3 view, but don't know how to do this. My code is following

我想在 asp.net mvc3 视图中调用 c# 代码中的 JavaScript 函数,但不知道如何执行此操作。我的代码如下

Javascript Function

Javascript 函数

function JK(){

   alert("Javascript Function Called From foreach");

  }

C# Foreach

C# Foreach

foreach(var item in collection){ //I want to call JavaScript function here on every iterate.  
}

采纳答案by Vladislav Qulin

Well you can use something like this:

那么你可以使用这样的东西:

foreach (var item in collection) {
   <script type="text/javascript">
     JK();
   </script>
}

If you need to use foreach inside the javascript code, you should just use . Like this:

如果您需要在 javascript 代码中使用 foreach,您应该只使用 . 像这样:

<script type="text/javascript">
   @foreach (var item in collection) {
      <text>JK();</text>
   }
</script>

回答by user854301

You can't call JS function on server side only in the views. And it wiil look like

您不能仅在视图中调用服务器端的 JS 函数。它看起来像

@foreach(var item in collection)
{
  ...
  <script type="text/javascript">
     JK()
  </script>
  ...
}

Output html will contain several calls of this js function.

输出 html 将包含此 js 函数的多个调用。

回答by Tx3

I would implement it little bit differently

我会以不同的方式实现它

@foreach(var item in collection)
{
    <!-- some html element that will be generated on each loop cycle
    <input type="hidden" class="item"/>
}

then with/without help of 3rd party JavaScript libraries

然后有/没有 3rd 方 JavaScript 库的帮助

$(document).ready(function () {
    $('.item').each(function () {
        JK();
    }
});

回答by ViPuL5

To call a javascript function

调用 javascript 函数

   //C# Code
@Html.Raw("CallFunction('" + @param + "');");
    //C# code..

Now for Javascript function

现在为 Javascript 功能

<script type="text/javascript">
     CallFunction(param)
     {
       alert(param);
     }
  </script>