最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - how to call a javascript function in foreach in mvc3 view - Stack Overflow

programmeradmin1浏览0评论

I want to call a JavaScript function in c# code in asp 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.  
}

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.  
}
Share Improve this question edited Aug 3, 2012 at 15:05 Pshemo 124k25 gold badges191 silver badges275 bronze badges asked Aug 3, 2012 at 5:14 user1573165user1573165 311 gold badge1 silver badge3 bronze badges 1
  • You would be better off using jQuery, assigning your DOM elements with a CSS class and using the jQuery.each. – lahsrah Commented Aug 3, 2012 at 5:16
Add a comment  | 

4 Answers 4

Reset to default 14

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>

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();
    }
});

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.

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)

  1. 暂无评论