how to call a javascript function in foreach in mv

2019-01-18 16:26发布

问题:

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

Javascript Function

function JK(){

   alert("Javascript Function Called From foreach");

  }

C# Foreach

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

回答1:

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:

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


回答2:

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

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


回答3:

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

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

Output html will contain several calls of this js function.



回答4:

To call a javascript function

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

Now for Javascript function

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