Tutorial :Using ASP.NET MVC and JQuery how do I run a JS function for each item in a list on load?


Imagine a view that is designed to show a list of items of type Foo:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Foo>>" %>  

Now the page displays the list of items of type Foo:

<table>          <tr>              <th>                  Name              </th>          </tr>        <% foreach (var item in Model) { %>          <tr>              <td>                  <%= Html.Encode(item.Name) %>              </td>          </tr>      <% } %>  </table>  

In addition to display the list of items on the page I also need to execute a Javascript function Bar for each of the items. Here's my first attempt:

<% foreach (var item in Model) { %>  <script type="text/javascript">        $(document).ready(function() {          var name = "<%=item.Name %>";          Bar(name)      });    </script>  <% } %>  

I get an error "Cannot resolve symbol item" against the line that begins "var name...".

Is this the correct way to achieve this? What's the correct syntax to use?


Try something like this:

<script type="text/javascript">      $(document).ready(function() {          $("table tr td").each(function() {              Bar(this.text());          });      });  </script>  

This script needs to be static and not generated by your View. Place it at the top of the page or put it in an external file and link to that file.


I'm not sure where your error is coming from (it may be because you are using double quotes, not single quotes for the code blocks), but you are also injecting a separate script element for each name. @Andrew's method would work well, but you could also do something like the below. It builds a javascript array (as a string) containing the names, then injects a single script block that iterates over the array elements and invokes the Bar function on each. I'd use @Andrew's method if you need to interact with the DOM elements themselves and, perhaps, this mechanism if you need to interact with only the data.

<% string names = "[";     foreach (var item in Model)     {        names = names + item.Name + ",";     }     names = names.TrimEnd(',') + "]";  %>    <script type="text/javascript">     $(function() {         $.each( <%= names %>, function(i,val) {            Bar(val);         });     });  </script>  


<script type="text/javascript">        $(document).ready(function() {          <% foreach (var item in Model) { %>              Bar('<%=item.Name %>');          <% } %>      });    </script>  

I'm using this, workes great, except that visual studio gets a bit confused.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »