how to call a javascript function in foreach in mvc3 view

后端 未结 4 1027
逝去的感伤
逝去的感伤 2020-12-10 09:12

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

相关标签:
4条回答
  • 2020-12-10 09:33

    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>
    
    0 讨论(0)
  • 2020-12-10 09:37

    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.

    0 讨论(0)
  • 2020-12-10 09:39

    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>
    
    0 讨论(0)
  • 2020-12-10 09:44

    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();
        }
    });
    
    0 讨论(0)
提交回复
热议问题