3

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
  • You would be better off using jQuery, assigning your DOM elements with a CSS class and using the jQuery.each. Commented Aug 3, 2012 at 5:16

4 Answers 4

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

Comments

-2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.